Catching exceptions

Errors & Exceptions, lesson 3 of 7

🛟 Errors & Exceptions, lesson 3 of 7

Catching exceptions

Handle errors gracefully with try/except instead of crashing.

10 min

1 exercise

1 quiz

0/2 solved

Getting Python ready… examples can run in a moment.

Not every error is a bug. Sometimes the data is bad: a user types "ten" instead of 10. With try/except you tell Python: try this, and if this specific error happens, do that instead.

try:
    risky_code()
except ValueError:
    plan_b()
Example

Safe number parsing

The loop keeps going after a bad value. Add "-4" or " 8 " to the list. Which ones parse?

Get the details with except ValueError as e:. The exception object e holds the message (str(e)).

Several except blocks are checked top to bottom; the first one that matches runs. To handle several types the same way, use a tuple: except (KeyError, IndexError):

Example

Different errors, different handling

When an except block doesn't return, the function returns None. That's why None appears. Try returning 0 from the ZeroDivisionError block.

Quiz

What does this print?

Exceptions come in families. Each exception type has a parent type, and except X: catches X and every type below it. For example, IndexError and KeyError are both kinds of LookupError.

Walkthrough

What does each except catch?

ExceptionLookupErrorIndexErrorKeyErrorValueErrorNameError
Step 1 of 4

A small part of the family tree. Almost every built-in error you have met sits somewhere under Exception.

caught
caught, but probably a bug
Example

Why a bare except is dangerous

The typo raises a NameError, but the bare except: swallows it, so every age looks invalid. Change except: to except ValueError: and run again: now the real bug is visible.

Exercise

Total the valid prices

Finish to_number(text): it should return float(text), or None when the text isn't a valid number. The loop below already uses it to add up only the valid prices.