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 moreexcept
clauses (and optionally anelse
clause)A
try
clause followed by exactly onefinally
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 ...
Get Python in a Nutshell, 2nd Edition 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.