Next / Previous / Contents / TCC Help System / NM Tech homepage

14.7. The try construct: catching exceptions

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:
    Bf

This construct specifies how you want to handle one or more exceptions that may occur during the execution of block Bt. Each except clause specifies one kind of exception you want to handle; the Ei part specifies which exception or exceptions, and the Li parts are destinations that receive data about the exception when it occurs.

Here is how a try block works:

  1. If no exception is raised during the execution of block Bt, the else block Bf is executed if there is one.

  2. If an exception is raised during block Bt, and it matches some exception type Ei, the corresponding block Bi is executed.

  3. If Bt raises an exception that doesn't match any of the except 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 X matches an except: clause Ei if they are the same exception, or if X is a subclass of Ei. See the discussion of the class structure of exceptions below.

There is another form of try block that is used to force execution of a cleanup block Bc no matter whether or not another block Bt causes an exception:

try:
    Bt
finally:
    Bc

If Bt raises any exception, block Bc is executed, then the same exception is raised again.