try语句有一个可选finally子句,用于定义在所有情况下都必须执行的finally操作
try:
raise KeyboardInterrupt
finally:
print('Goodbye, world!')
Goodbye, world!
KeyboardInterrupt
Traceback (most recent call last):
File "", line 2, in
如果存在finally子句,则该finally子句将作为try语句完成之前的最后一项任务执行。finally无论该try语句是否产生异常,该子句都会运行。
以下几点讨论了发生异常时更复杂的情况:
如果在执行该try子句期间发生异常,则该异常可以由except子句处理。如果该异常未由except子句处理,finally则在执行该子句后将重新引发该异常。
执行exceptor else子句期间可能会发生异常。同样,在finally执行该子句之后,将重新引发异常。
如果try语句到达break,continue或return语句时,finally条款将在break,continue或return语句之前执行。
如果finally子句包含一条return语句,则该finally子句的return语句将在子句中的return语句之前执行,所以事实上执行了的是finally的return,而不是在中执行return语句。
案例1.
>>> def bool_return():
... try:
... return True
... finally:
... return False
...
>>> bool_return()
False
案例2.
def bool_return():
try:
raise Exception
except Exception:
return True
finally:
return False
print(bool_return())
False
案例3.
>>> def divide(x, y):
... try:
... result = x / y
... except ZeroDivisionError:
... print("division by zero!")
... else:
... print("result is", result)
... finally:
... print("executing finally clause")
...
>>> divide(2, 1)
result is 2.0
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Traceback (most recent call last):
File "", line 1, in
File "", line 3, in divide
TypeError: unsupported operand type(s) for /: 'str' and 'str'