[英]How to handle exception chaining raised from the except block
在我的示例中,我有一個自定義異常類MyCustomException
,在main中我將一個整數a
除以零,這會引發ZeroDivisionError
異常。 使用except塊我捕獲ZeroDivisionError
,然后從err
引發MyCustomException
; 這創建了一個鏈式異常,我自己,加上err
異常。
現在我如何捕獲鏈式異常或鏈式異常如何工作? Python不允許我在我的代碼中捕獲except
塊except
MyCustomException
。
class MyCustomException(Exception):
pass
a=10
b=0
reuslt=None
try:
result=a/b
except ZeroDivisionError as err:
print("ZeroDivisionError -- ",err)
raise MyCustomException from err
except MyCustomException as e:
print("MyException",e) # unable to catch MyCustomException
我執行它時得到的輸出:
ZeroDivisionError -- division by zero
Traceback (most recent call last):
File "python", line 13, in <module>
MyCustomException
在except
子句中使用raise
將不會在同一個try
塊中搜索異常處理程序( 它在try
塊中沒有出現 )。
它將在一級搜索處理程序,即外部try
塊。 如果沒有找到它,它將像通常那樣中斷執行(導致顯示異常)。
簡而言之, except MyCustomException
,您需要在外層使用相應的try
來捕獲自定義異常:
try:
try:
result=a/b
except ZeroDivisionError as err:
print("ZeroDivisionError -- ",err)
raise MyCustomException from err
except MyCustomException as e:
print("Caught MyException", e)
執行時,現在打印出:
ZeroDivisionError -- division by zero
Caught MyException
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.