Catching exceptions

Errors & Exceptions, lesson 3 of 6

🛟 Errors & Exceptions, lesson 3 of 6

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?

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.