我的代码中有这个try
块:
try:
do_something_that_might_raise_an_exception()
except ValueError as err:
errmsg = 'My custom error message.'
raise ValueError(errmsg)
严格地说,我实际上是在提升另一个{do_something...()
抛出的ValueError
,在本例中称为err
。如何将自定义邮件附加到err
?我尝试了以下代码,但由于实例err
、实例ValueError
不可调用而失败:
try:
do_something_that_might_raise_an_exception()
except ValueError as err:
errmsg = 'My custom error message.'
raise err(errmsg)
印刷品:
更新:对于Python 3,请选中Ben's answer
要将消息附加到当前异常并重新引发它,请执行以下操作: (外部尝试/例外只是为了显示效果)
对于python 2.x,其中x>;=6:
如果
err
是从ValueError
派生的,这也将做正确的事情。例如UnicodeDecodeError
。注意,您可以添加任何您喜欢的内容到
err
。例如err.problematic_array=[1,2,3]
。编辑:@Ducan points在注释中,由于
.message
不是ValueError
的成员,以上内容不适用于python 3。相反,您可以使用它(有效的Python2.6或更高版本或3.x):编辑2:
根据用途,您还可以选择在自己的变量名下添加额外信息。对于python2和python3:
我意识到这个问题已经出现了一段时间,但是一旦你足够幸运地只支持Python3.x,这真的就变成了一件美妙的事情:)
从
我们可以使用raise from链接异常。
在这种情况下,调用者将捕获的异常具有引发异常的地方的行号。
请注意,底部异常仅具有引发异常的stacktrace。调用方仍然可以通过访问它们捕获的异常的
__cause__
属性来获取原始异常。带回溯
或者你可以使用with_traceback。
使用此表单,调用者将捕获的异常具有原始错误发生位置的回溯。
请注意,底部的异常有执行无效除法的行和重新引发异常的行。
相关问题 更多 >
编程相关推荐