捕获多个异常

有几种方法可以捕获多个异常

第一种方法是创建一个你希望以相同方式捕获和处理的异常类型的元组。此示例将导致代码忽略 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)