![](/img/trans.png)
[英]Is there a way in python to execute a piece of code only if any exception is raised in a try/except block?
[英]In python, is there a way to enter a try/except block if a condition is met, otherwise execute the code in the try block plainly?
我想執行一個嘗試運行代碼塊的循環,並跳過任何碰巧失敗的迭代。 但是,我也希望能夠傳入一個調試標志,這樣如果其中一個迭代失敗,程序就會崩潰,用戶可以查看回溯以幫助自己查看失敗的位置。 基本上,我想這樣做:
debug = False # or True
for i in range(10):
if not debug:
try:
# many lines of code
except:
print(f'Case {i} failed')
else:
# many lines of code
但是,我不想重復#many lines of code
。 我可以將它們包裝在一個輔助函數中並精確地執行我上面寫的結構,但是我將不得不傳遞一堆會增加一些復雜性的變量(也就是我不想編寫的單元測試)。 有沒有另一種方法可以做到這一點?
避免將many lines of code
分解為自己的函數(這通常是一個好主意,但並非總是如此)的最佳解決方案是無條件使用try
/ except
,但讓except
有條件地重新引發異常:
debug = False # or True
for i in range(10):
try:
# many lines of code
except:
if debug:
raise # Bare raise reraises the exception as if it was never caught
print(f'Case {i} failed')
一個捕獲的異常被一個空的raise
沒有留下用戶可見的痕跡來區分它與未捕獲的異常; 回溯沒有變化,沒有任何跡象表明它通過了except
塊,因此凈效果與您的原始代碼相同,除了稍后評估debug
(如果沒有異常發生,則根本不會)和many lines of code
只出現一次.
旁注: except
塊except
裸露是一個壞主意。 如果不出意外,請將其限制為except Exception:
這樣您就不會在非調試模式下捕獲和抑制諸如KeyboardInterrupt
或SystemExit
類的東西。
最好的方法是使用一個函數,多一行也無所謂。
否則,如果不需要測試debug
,則不需要重復else
塊。 因為如果try
語句不會引發錯誤,那么它將執行並且結果將正常顯示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.