Python has a wonderfully flexible and general
error-handling mechanism using
exceptions. Whenever a program
cannot proceed normally due to some problem, it can
raise an exception. For example,
there is a built-in exception called
ZeroDivisionError that occurs
whenever someone tries to divide by zero. You can also
define your own kinds of exceptions. See
exceptions
below for more information about exception types.
Typically, an exception will terminate execution
of the program. However, you can use Python's
try construct to
handle exceptions, that is, take
some other action when they occur.
The most general form of the construct looks like this:
try:
Bt
except E1, L1:
B1
except E2, L2:
B2
...
else:
BfThis construct specifies how you want to handle
one or more exceptions that may occur during the
execution of block
.
Each Btexcept clause specifies one
kind of exception you want to handle; the
part specifies which exception or exceptions, and the
Ei
parts are destinations that receive data about the
exception when it occurs.Li
You can omit
the part.Li
You can omit both
the
and the
Li parts.
In that case, the Eiexcept
clause matches all types of exceptions.
Here is how a try block works:
If no exception is raised during the execution of block
,
the Btelse block
is executed if there is one.Bf
If an exception is raised during block
,
and it matches some exception type
Bt,
the corresponding block
Ei is executed.Bi
If
raises an exception that doesn't match any of the
Btexcept clauses, program
execution is terminated and a message shows the
exception and a traceback of the program.
The built-in exceptions are arranged in a
hierarchy structure of base classes and classes
derived from them. An exception
matches an
Xexcept: clause
if they are the same exception, or if
Ei is a subclass of
X.
See the discussion of
the class structure of
exceptions below.Ei
There is another form of try
block that is used to force execution of a cleanup block
no matter whether or not another block
Bc causes an exception:Bt
try:
Bt
finally:
BcIf
raises any exception, block
Bt
is executed, then the same exception is raised again.Bc