Stage 1 · Lesson 8 of 9
Handling errors with exceptions
Some errors are expected. A user types "abc" when you asked for a number, or a file is missing. try and except handle these without crashing the program.
Put the risky line inside try, catch the specific , such as ValueError or FileNotFoundError, and respond with a clear message or a retry. Catch the narrowest exception you can. A bare except: catches everything, so it hides real bugs, including typos in your own code.
An else block runs when nothing failed, and finally always runs, which suits clean-up work such as closing a file. You can raise your own exceptions too, such as raise ValueError("age must be positive"), to stop bad data early. Combine this with a to keep asking until the value is valid.
A question to check yourself, an AI practice session and 1 cheat sheet entry come when you add the roadmap to your account. Add it
Resources for this stage
Start with· follow one of these
- CoursePaidGrokking Python Fundamentals
Design Gurus · Beginner · $50
Beginner Python with an in-browser exercise after nearly every lesson
- CourseFreeCS50's Introduction to Programming with Python
Harvard University · Beginner
Free Harvard course whose weekly problem sets make you write real programs