捕獲多個異常

有幾種方法可以捕獲多個異常

第一種方法是建立一個你希望以相同方式捕獲和處理的異常型別的元組。此示例將導致程式碼忽略 KeyErrorAttributeError 異常。

try:
    d = {}
    a = d[1]
    b = d.non_existing_field
except (KeyError, AttributeError) as e:
    print("A KeyError or an AttributeError exception has been caught.")

如果希望以不同方式處理不同的異常,可以為每種型別提供單獨的異常塊。在這個例子中,我們仍然捕獲 KeyErrorAttributeError,但以不同的方式處理異常。

try:
    d = {}
    a = d[1]
    b = d.non_existing_field
except KeyError as e:
    print("A KeyError has occurred. Exception message:", e)
except AttributeError as e:
    print("An AttributeError has occurred. Exception message:", e)