Error Handling

Catching multiple exception types

Real code can fail in more than one way. Learn how to attach several except blocks to a single try, group exceptions in a tuple, and use a generic Exception as a last resort.


Real code can fail in more than one way. A single try block can be paired with several except clauses, each handling a different exception type.

Here we react differently depending on what went wrong:

Python
Output

Python checks each except in order. The first one that matches the exception runs, the rest are skipped.


What will be the output?

Python

When two exceptions deserve the same response, group them in a tuple after a single except keyword.

One block, two exception types:

Python
Output

What will be the output?

Python

Python exceptions form a hierarchy. IndexError and KeyError both inherit from LookupError, so catching the parent catches both.

A LookupError except catches an IndexError:

Python
Output

And the same except also catches a KeyError, since KeyError is a child of LookupError too.

Same except, different exception:

Python
Output

What will be the output?

Python

At the top of the hierarchy sits Exception. Catching it grabs almost any error. Use it as a last resort — it can hide real bugs.

A generic Exception with as captures the message:

Python
Output

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python