Python 101Free
CONTROL FLOW

Exceptions

What happens when things go wrong, and how to recover.

SECTION 01

try and except

Wrap risky code in a try block. If something inside raises an exception, control jumps to the matching except block instead of crashing the program. The except clause names which exception class to catch (or which classes, in a tuple).

A bare except: catches everything, including keyboard interrupts and system exits. Avoid it. If you do not know which exception to catch, catch Exception instead, which leaves the truly fatal ones alone.

The goal is not to suppress every error. The goal is to handle the specific cases you can recover from, and let the rest crash loudly so you can fix them.

python
try:
    n = int(user_input)
except ValueError:
    n = 0   # fall back when the input cannot be parsed
2 more sections

Create a free account to access all sections and animations.

Create free accountAlready have an account? Sign in