为什么此代码不起作用?
def test():
e = None
try:
raise Exception
except Exception as e:
pass
return e
test()
我收到此错误:
UnboundLocalError:分配前引用了本地变量'e'
答案 0 :(得分:7)
捕获到异常并将其绑定到名称后,该名称将在try
语句之后清除。来自documentation of the try
statement:
except E as N:
foo
与
相同except E as N:
try:
foo
finally:
del N
因此,如果捕获到异常,则e
一旦到达return e
就不再存在。这样做是为了打破堆栈帧(包含对e
的引用)和e
引用的回溯(包含对堆栈帧的引用)之间的引用周期。>