簡體   English   中英

Python:最終需要一個try-except子句嗎?

[英]Python: Does finally needs a try-except clause?

假設以下代碼。

try:
    some_code_1
except: # will it be called twice, if an error occures in finally?
    some_code_2
finally:
    some_code_3

假設some_code_3發生異常。 我是否需要在some_code_3周圍使用額外的try-except子句(見下文),或者是否會再次調用some_code_2的異常,這原則上會導致無限循環?

這是救星嗎?

try:
    some_code_1
except: # will it be called twice, if an error occures in finally?
    some_code_2
finally:
    try:
        some_code_3
    except:
        pass

試一試:

try:
    print(abc) #Will raise NameError
except: 
    print("In exception")
finally:
    print(xyz) #Will raise NameError

Output: 
In exception
Traceback (most recent call last):
  File "Z:/test/test.py", line 7, in <module>
    print(xyz)
NameError: name 'xyz' is not defined

所以不,它不會以無限循環結束

python不會返回執行流程,而是聲明語句。

當它到達finally ,如果在那里拋出錯誤,它還需要另一個句柄

示例代碼中的finally不會從some_code_3中捕獲異常。

是否需要從some_code_3捕獲異常取決於您的設計。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM