Exception Catching Modes

Now that we’ve taken a first look, let’s fill in a few details behind Python’s exception model.

try Statement Clauses

When you write try statements, a variety of clauses can appear after the try statement block; Table 7.1 summarizes all the possible forms. We’ve already seen most of these in the previous examples—empty except clauses catch any exception, finally runs on the way out, and so on. There may be any number of excepts, but finally must appear by itself (without an else or except), and there should be only one else in a try.

Table 7-1. try Statement Clause Forms

Clause Form

Interpretation

except:

Catch all (other) exception types

except name:

Catch a specific exception only

except name, value:

Catch exception and its extra data

except (name1, name2):

Catch any of the listed exceptions

else:

Run block if no exceptions raised

finally:

Always perform block

Catching 1-of-N Exceptions

The fourth entry in Table 7.1 is new. except clauses can also provide a set of exceptions to be caught, in parentheses; Python runs such a clause’s statement block if any of the listed exceptions occur. Since Python looks for a match within a given try by inspecting except clauses from top to bottom, the parenthesized version is like listing each exception in its own except clause, except that the statement body needs to be coded only once.

Here’s an example of multiple except clauses at work. In the following, when an exception is raised while the call to the ...

Get Learning Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.