UnboundLocalError:赋值之前引用了局部变量“ e”

时间:2020-06-07 19:00:26

标签: python python-3.x exception

为什么此代码不起作用?

def test():   
    e = None
    try:
        raise Exception

    except Exception as e:
        pass

    return e

test()

我收到此错误:

UnboundLocalError:分配前引用了本地变量'e'

1 个答案:

答案 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引用的回溯(包含对堆栈帧的引用)之间的引用周期。