我正在试验 Python 装饰器以了解它发生了什么,但我遇到了一个令人头疼的问题。
我的代码是这样的(python 2.7.6):
import traceback
def dec(func):
def wrapped(*args, **kwargs):
try:
if flag:
print 'flagged'
else:
print 'unflagged'
except NameError as e:
print 'error?'
raise
finally:
return func(*args, **kwargs)
return wrapped
@dec
def foo(x):
print x
foo(3)
运行时,输出为:
error?
3
我预计调用 foo(3) 会引发:
NameError: global name 'flag' is not defined
为什么“加薪”不加薪?显然,错误已被捕获 - Except block 中的打印已执行...
请您参考如下方法:
finally 中的return 覆盖并取消可能触发finally block 的任何异常或函数返回。这记录在 Python Language Reference 中:
If
finallyis present, it specifies a ‘cleanup’ handler. Thetryclause is executed, including anyexceptandelseclauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. Thefinallyclause is executed. If there is a saved exception, it is re-raised at the end of thefinallyclause. If thefinallyclause raises another exception or executes areturnorbreakstatement, the saved exception is discarded:
例如:
def f():
try:
1/0
finally:
return
f() # No exception
def g():
try:
return 1
finally:
return 0
g() # 0
def h():
try:
raise NameError
finally:
raise TypeError
h() # TypeError
