为什么这段代码不起作用?
def test():
e = None
try:
raise Exception
except Exception as e:
pass
return e
test()
我收到此错误:
UnboundLocalError:分配前引用的局部变量“e”
最佳答案
当异常被捕获并绑定(bind)到一个名称时,该名称在 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
引用的回溯之间的引用循环。 (其中包含对堆栈帧的引用)。
关于python - UnboundLocalError : local variable 'e' referenced before assignment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62250236/