Python try and except: Handling Errors Gracefully
When something goes wrong while a program runs, such as dividing by zero or converting "abc" to a number, Python raises an exception. If nothing handles it, the program stops and prints a traceback ending in a line like ValueError: invalid literal for int() with base 10: 'abc'. Read tracebacks from the bottom: the last line names the exception type and the message, and the lines above show where it happened.
try and except
Put code that might fail inside try:, and the recovery code inside except SomeError:. If the try block raises an exception of that type, Python jumps straight to the except block; otherwise the except block is skipped. Write except ValueError as err: to get the exception object, whose text explains what happened.
Always catch the specific exception you expect. A bare except: also catches typos in your own code and even Ctrl+C, hiding bugs instead of handling errors.
else and finally
else:runs only if thetryblock finished without an exception. It keeps thetryblock small, containing just the line that might fail.finally:runs no matter what, even after areturn. Use it for cleanup, such as closing a connection. For files, thewithstatement (see the files chapter) does this for you.
Expected output
42 '4.2' is not a whole number None Error: division by zero finally always runs Refused: insufficient funds
Raising your own exceptions
Use raise when your function receives input it cannot work with. withdraw() raises ValueError with a clear message instead of returning a confusing value, and the caller decides what to do. Pick a built-in type that fits: ValueError for a bad value, TypeError for the wrong kind of object, KeyError or LookupError for something missing.
Common error types
NameError (unknown name), TypeError (wrong type for an operation), ValueError (right type, bad value), IndexError and KeyError (missing position or key), ZeroDivisionError, FileNotFoundError and AttributeError (no such method or attribute). Recognizing them saves debugging time.
Common mistakes
- Wrapping a whole program in one
tryblock, so you cannot tell which line failed. - Silently passing:
except ValueError: passhides problems. At least log a message. - Catching
Exceptionwhen you only expected one specific error.
Summary
try/exceptcatches exceptions so the program can recover.- Catch specific types; read tracebacks from the bottom up.
elseruns on success,finallyalways runs.raise ValueError("message")signals bad input from your own code.
Quiz: Errors and exceptions