[英]How to handle exception chaining raised from the except block
在我的示例中,我有一个自定义异常类MyCustomException
,在main中我将一个整数a
除以零,这会引发ZeroDivisionError
异常。 使用except块我捕获ZeroDivisionError
,然后从err
引发MyCustomException
; 这创建了一个链式异常,我自己,加上err
异常。
现在我如何捕获链式异常或链式异常如何工作? Python不允许我在我的代码中捕获except
块except
MyCustomException
。
class MyCustomException(Exception):
pass
a=10
b=0
reuslt=None
try:
result=a/b
except ZeroDivisionError as err:
print("ZeroDivisionError -- ",err)
raise MyCustomException from err
except MyCustomException as e:
print("MyException",e) # unable to catch MyCustomException
我执行它时得到的输出:
ZeroDivisionError -- division by zero
Traceback (most recent call last):
File "python", line 13, in <module>
MyCustomException
在except
子句中使用raise
将不会在同一个try
块中搜索异常处理程序( 它在try
块中没有出现 )。
它将在一级搜索处理程序,即外部try
块。 如果没有找到它,它将像通常那样中断执行(导致显示异常)。
简而言之, except MyCustomException
,您需要在外层使用相应的try
来捕获自定义异常:
try:
try:
result=a/b
except ZeroDivisionError as err:
print("ZeroDivisionError -- ",err)
raise MyCustomException from err
except MyCustomException as e:
print("Caught MyException", e)
执行时,现在打印出:
ZeroDivisionError -- division by zero
Caught MyException
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.