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 checks each except in order. The first one that matches the exception runs, the rest are skipped.
What will be the output?
When two exceptions deserve the same response, group them in a tuple after a single except keyword.
One block, two exception types:
What will be the output?
Python exceptions form a hierarchy. IndexError and KeyError both inherit from LookupError, so catching the parent catches both.
A LookupError except catches an IndexError:
And the same except also catches a KeyError, since KeyError is a child of LookupError too.
Same except, different exception:
What will be the output?
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:
What will be the output?
What will be the output?
What will be the output?
What will be the output?