我假设以下代码应该打印 (“CustomExceptionALL”),但如果我们引发 CustomException1CustomException2或CustomException3在CustomExceptionALL工作时,这种情况永远不会发生。为什么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)
Run Code Online (Sandbox Code Playgroud)
用例更多地是相反的:引发派生异常,然后使用父类捕获它。例如:
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2218 次 |
| 最近记录: |