the try statement¶
try_stmt ::= try1_stmt | try2_stmt
try1_stmt ::= “try” “:” suite
(“except” [expression [“as” identifier]] “:” suite)+
[“else” “:” suite]
[“finally” “:” suite]
try2_stmt ::= “try” “:” suite
“finally” “:” suite
- expression-less except
!Note: An expression-less except clause, if present, must be last; it matches any exception.(expression-less except: 缺少 expression 的 except: 即为
except:
)
try:
some code ...
except exc_A:
some handle code ...
except exc_B:
some handle code ...
except: # the last
some handle code ...
- compatible
For an except clause with an expression, that expression is evaluated, and the clause matches the exception if the resulting object is “compatible” with the exception. An object is compatible with an exception if it is the class or a base class of the exception object or a tuple containing an item compatible with the exception.
- So, all user-defined exceptions should also be derived from this class: Exception.
- a tuple of exceptions
expression ::= (exc_1, exc_2, ... , exc_N)
try:
1/0
except (ZeroDivisionError, IOError) as e:
print(str(e))
...
division by zero
- as
When a matching except clause is found, the exception is assigned to the target specified after theas
keyword in that except clause
When an exception has been assigned usingas target
, it is cleared at the end of the except clause. This is as if
except E as N:
foo
was translated to
except E as N:
try:
foo
finally:
del N
- else
The optional else
clause is executed if and when control flows off the end of the try clause. Exceptions in the else
clause are not handled by the preceding except clauses.
- finally
If finally
is present, it specifies a ‘cleanup’ handler. The try
clause is executed, including any except
and else clauses
. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally
clause is executed. If there is a saved exception it is re-raised at the end of the finally
clause. If the finally
clause raises another exception, the saved exception is set as the context of the new exception.
>>> try:
... 1/0
... finally:
... print("what's up?")
... raise ValueError
...
what's up? # print in finally statement
Traceback (most recent call last): # re-raised and set as __context__ of ValueError()
File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 5, in <module>
ValueError
If the finally
clause executes a return or break statement, the saved exception is discarded:
>>> def f():
... try:
... 1/0
... finally:
... return 42
...
>>> f() # the saved exception is discarded.
42
The return value of a function is determined by the last return statement executed. Since the finally
clause always executes, a return statement executed in the finally
clause will always be the last one executed:
>>> def foo():
... try:
... return 'try'
... finally:
... return 'finally'
...
>>> foo()
'finally'