有人可以幫我理解這里發生了什么。我對變數范圍在 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中有詳細說明的鏈接,請您幫忙。
uj5u.com熱心網友回復:
區塊開始
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/426254.html
標籤:Python python-3.x 例外 python-闭包
下一篇:NumberFormatExcpetion同時使用Long.parseLong()將base-2數字(作為字串)決議為base-10Longint
