1

有人可以帮我理解这里发生了什么。我对变量范围在 python 中的工作方式有一些了解。
当这段代码运行时,我得到一个错误:

rec = True

    try:
        print("outer try")
        raise Exception("outer exception")
    except Exception as msg:
        try:
            rec = True
            print("inner try")
            raise Exception("inner exception")
        except Exception as msg:
            rec = False
            print(str(msg))
        
        if rec == False:
            print(str(msg))

输出错误:
outer try
inner try
inner exception

---------------------------------------------------------------------------
Exception Traceback (most recent call last)
<ipython-input-2-6ce9b26112ed> in <module>
      5     print("outer try")
----> 6     raise Exception("outer exception")
      7 except Exception as msg:

Exception: outer exception

During handling of the above exception, another exception occurred:

NameError Traceback (most recent call last)
<ipython-input-2-6ce9b26112ed> in <module>
     15 
     16     if rec == False:
---> 17         print(str(msg))

NameError: name 'msg' is not defined

我的理解是,当调用并完成内部异常时,“msg”变量将变为未设置或从内存中删除。

现在,当我运行这段代码时,它运行成功:
rec = True

try:
    print("outer try")
    raise Exception("outer exception")
except Exception as outer_msg:
    try:
        rec = True
        print("inner try")
        raise Exception("inner exception")
    except Exception as msg:
        rec = False
        print(str(msg))
    
    if rec == False:
        print(str(outer_msg))

输出:

outer try
inner try
inner exception
outer exception

此错误与“变量范围”或“闭包”有关吗?如果有人在python中有详细说明的链接,请您帮忙。

4

1 回答 1

1

区块开始

except Exception as msg:

在块的开头创建msg变量,并在块的末尾删除它。已经存在的msg变量在同一个作用域内同名,所以被覆盖然后删除。

如果要跟踪两个异常,则需要为两个异常使用单独的名称,因为它们在同一范围内。

请参阅https://docs.python.org/3/reference/compound_stmts.html#the-try-statement,其中说:

当使用 分配异常时as target,它会在 except 子句的末尾被清除。这仿佛

except E as N:
    foo

被翻译成

except E as N:
    try:
        foo
    finally:
        del N
于 2022-02-03T12:52:34.097 回答