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.

try: ... except ValueError: ...\texttt{try: ... except ValueError: ...}catch a specific error type
finally: ...\texttt{finally: ...}always runs, with or without an error
raise ValueError("...")\texttt{raise ValueError("...")}raise an error yourself

Symbols

ValueError\texttt{ValueError}bad value, e.g. int("abc")
ZeroDivisionError\texttt{ZeroDivisionError}division by zero
FileNotFoundError\texttt{FileNotFoundError}the file does not exist

Example

Read a number safely from the user:

try: x = float(s)\texttt{try: x = float(s)}, and on except ValueError\texttt{except ValueError} ask again.

Catch errors as specifically as possible. A bare except hides real programming mistakes.
Practise files, errors and modules for free →

← Reading and writing files · Modules and import →

Part of Programming with Python: Files, errors and modules.