All courses › Programming with Python › Error handling
Error handling
When something goes wrong at run time, Python raises an exception, for example ValueError when text cannot be turned into a number. With try and except you catch the exception and decide what happens, instead of the program crashing.
catch a specific error type
always runs, with or without an error
raise an error yourself
Symbols
| bad value, e.g. int("abc") | ||
| division by zero | ||
| the file does not exist |
Example
Read a number safely from the user:
, and on ask again.
Catch errors as specifically as possible. A bare except hides real programming mistakes.
Practise files, errors and modules for free →