我假设下面的代码应该打印(“CustomExceptional”),但如果我们在CustomExceptionALL
工作时引发CustomException1、CustomException2
或CustomException3
,则永远不会发生这种情况。为什么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)
因为您只能捕获指定异常的子类。在您的情况下,这两个是错误的:
(因为您正试图捕获
CustomExceptionALL
,但CustomException3
不是CustomExceptionALL
,而是相反)您可以改为使用类的元组:
用例则是相反的:您引发派生异常,然后使用父类捕获它。例如:
相关问题 更多 >
编程相关推荐