gpt4 book ai didi

python - 为什么一个多重继承的Exception没有捕捉到父异常?

转载 作者:行者123 更新时间:2023-12-01 21:30:50 26 4
gpt4 key购买 nike

我假设以下代码假设打印 ("CustomExceptionALL"),但如果我们在 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)

最佳答案

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

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)

关于python - 为什么一个多重继承的Exception没有捕捉到父异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62479857/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com