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
tryclause followed by one or moreexceptclauses (and optionally anelseclause)A
tryclause followed by exactly onefinallyclause
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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access