我的代码中有这个 try
block :
try:
do_something_that_might_raise_an_exception()
except ValueError as err:
errmsg = 'My custom error message.'
raise ValueError(errmsg)
严格来说,我其实是在提出另一个 ValueError
,而不是do_something...()抛出的
code>,在这种情况下称为 ValueError
err
。如何将自定义消息附加到 err
?我尝试以下代码,但由于 err
失败,ValueError
instance,不可调用:
try:
do_something_that_might_raise_an_exception()
except ValueError as err:
errmsg = 'My custom error message.'
raise err(errmsg)
最佳答案
如果你有幸只支持 python 3.x,这真的是一件很美的事情:)
提高
我们可以使用 raise from 链接异常。 .
try:
1 / 0
except ZeroDivisionError as e:
raise Exception('Smelly socks') from e
在这种情况下,您的调用者将捕获的异常具有我们引发异常的位置的行号。
Traceback (most recent call last):
File "test.py", line 2, in <module>
1 / 0
ZeroDivisionError: division by zero
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "test.py", line 4, in <module>
raise Exception('Smelly socks') from e
Exception: Smelly socks
请注意,底部异常只有我们引发异常的堆栈跟踪。您的调用者仍然可以通过访问他们捕获的异常的 __cause__
属性来获取原始异常。
with_traceback
或者您可以使用 with_traceback .
try:
1 / 0
except ZeroDivisionError as e:
raise Exception('Smelly socks').with_traceback(e.__traceback__)
使用此表单,您的调用者将捕获的异常具有原始错误发生位置的回溯。
Traceback (most recent call last):
File "test.py", line 2, in <module>
1 / 0
ZeroDivisionError: division by zero
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "test.py", line 4, in <module>
raise Exception('Smelly socks').with_traceback(e.__traceback__)
File "test.py", line 2, in <module>
1 / 0
Exception: Smelly socks
请注意,底部异常包含我们执行无效除法的行以及我们重新引发异常的行。
关于python - 如何在 Python 中使用自定义消息引发相同的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9157210/