为什么多重继承异常不能捕获父异常?

2024-09-19 23:42:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我假设下面的代码应该打印(“CustomExceptional”),但如果我们在CustomExceptionALL工作时引发CustomException1、CustomException2CustomException3,则永远不会发生这种情况。为什么except CustomExceptionALL没有抓住CustomException3

class CustomException1(Exception):
    pass

class CustomException2(Exception):
    pass

class CustomException3(Exception):
    pass

class CustomExceptionALL(CustomException1, CustomException2, CustomException3):
    pass

try:
    raise CustomException3
except CustomExceptionALL as e:
    print("CustomExceptionALL")
except Exception as e:
    print(e)

Tags: 代码asexception情况passclassraiseprint
2条回答

因为您只能捕获指定异常的子类。在您的情况下,这两个是错误的:

isinstance(CustomException3(), CustomExceptionALL)  # False
issubclass(CustomException3, CustomExceptionALL)  # False

(因为您正试图捕获CustomExceptionALL,但CustomException3不是CustomExceptionALL,而是相反)

您可以改为使用类的元组:

CustomExceptionALL = (CustomException1, CustomException2, CustomException3)

isinstance(CustomException3(), CustomExceptionALL)  # True
issubclass(CustomException3, CustomExceptionALL)  # True

try:
    raise CustomException3
except CustomExceptionALL as e:
    print("CustomExceptionALL")  # This prints
except Exception as e:
    print(e)

用例则是相反的:您引发派生异常,然后使用父类捕获它。例如:

class Brexit(Exception):
    pass

class Covid(Exception):
    pass

class DoubleWhammy(Brexit, Covid):
    pass

try:
    raise DoubleWhammy
except Brexit as e:
    print("Brexit")
except Exception as e:
    print(e)

相关问题 更多 >