有人可以帮我理解这里发生了什么。我对变量范围在 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中有详细说明的链接,请您帮忙。