![](/img/trans.png)
[英]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?
[英]Is there a way in python to execute a piece of code only if any exception is raised in a try/except block?
我有一個帶有多個 except 塊的try/except
except 塊。 我希望只有在引發任何異常時才能執行一段代碼。 有點像finally
語句,但無論是否引發異常, finally
執行。 我是否只需將該代碼添加到每個except
塊中?
您可以在異常處理程序中進行自己的類型檢查,以處理特定於類型的代碼和通用代碼。
def it_will_end_in_tears():
raise ValueError("bad value")
try:
val = it_will_end_in_tears()
except (TypeError, ValueError) as e:
if isinstance(e, TypeError):
print("type error stuff")
elif isinstance(e, ValueError):
print("value error stuff")
print("common stuff")
finally:
print("finally")
我不會將代碼復制+粘貼到每個 except 塊中,而是聲明一個布爾值execute_code = False
並將其在每個 except 塊中設置為True
。 在整個try/except
,添加if execute_code:
,然后在if
塊內實現一次發生異常時執行的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.