loop
Exceptions

Module 4 · Exceptions · Lesson 3 of 6

Handling several kinds

The same try block can fail in more than one way. Our little program raises a ValueError on bad text — but enter 0 and the division raises a ZeroDivisionError instead. You can give each its own handler by stacking multiple except branches.

First matching handler wins
⚠ ZeroDivisionError raised
except ValueError:
except ZeroDivisionError:
except except: (any)

The bare except: catches anything not named above — so it must always come last.

When an exception is raised, Python checks the except branches top to bottom and runs the first one that matches — then skips all the others. Each error type should appear at most once.

You can also add a bare except: with no type — a catch-all for anything you didn't name. Because it matches everything, it must always be the last branch, or it would swallow errors before the specific handlers get a chance.

Run it yourselfruns in your browser · Python
main.py

A word of care with the catch-all: it's convenient, but hiding every error can mask real bugs. Prefer naming the exceptions you actually expect. To do that well, it helps to know the usual suspects — coming up next.