O'Reilly logo

Python in a Nutshell, 2nd Edition by Alex Martelli

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The try Statement

The try statement provides Python’s exception-handling mechanism. It is a compound statement that can take one of two different forms:

  • A try clause followed by one or more except clauses (and optionally an else clause)

  • A try clause followed by exactly one finally clause

In Python 2.5, a try statement can have except clauses (and optionally an else clause) followed by a finally clause; however, in all previous versions of Python, the two forms cannot be merged, so I present them separately in the following. See The try/except/finally statement for this small 2.5 enhancement to try statement syntax.

try/except

Here’s the syntax for the try/except form of the try statement:

try:
    statement(s)
except [expression [, target]]:
    statement(s)
[else:
    statement(s)]

This form of the try statement has one or more except clauses, as well as an optional else clause.

The body of each except clause is known as an exception handler. The code executes if the expression in the except clause matches an exception object propagating from the try clause. expression is a class or tuple of classes, and matches any instance of one of those classes or any of their subclasses. The optional target is an identifier that names a variable that Python binds to the exception object just before the exception handler executes. A handler can also obtain the current exception object by calling the exc_info function of module sys (covered in exc_info in The sys Module).

Here is an example of the try/except form ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required