簡體   English   中英

如何處理從except塊引發的異常鏈接

[英]How to handle exception chaining raised from the except block

在我的示例中,我有一個自定義異常類MyCustomException ,在main中我將一個整數a除以零,這會引發ZeroDivisionError異常。 使用except塊我捕獲ZeroDivisionError ,然后從err引發MyCustomException ; 這創建了一個鏈式異常,我自己,加上err異常。

現在我如何捕獲鏈式異常或鏈式異常如何工作? Python不允許我在我的代碼中捕獲exceptexcept 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.

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