我在我的代码中有这个try块:
try:
do_something_that_might_raise_an_exception()
except ValueError as err:
errmsg = 'My custom error message.'
raise ValueError(errmsg)
严格地说,我实际上引发了另一个ValueError,而不是do_something…()抛出的ValueError,在这种情况下被称为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的答案
将一条消息附加到当前异常并重新引发:
(外面的try/except只是为了展示效果)
对于python 2。其中X >=6:
try:
try:
raise ValueError # something bad...
except ValueError as err:
err.message=err.message+" hello"
raise # re-raise current exception
except ValueError as e:
print(" got error of type "+ str(type(e))+" with message " +e.message)
如果err是从ValueError派生的,这也会做正确的事情。例如UnicodeDecodeError。
请注意,您可以添加任何您喜欢的错误。例如err.problematic_array=[1,2,3]。
编辑:@Ducan在注释中指出,上述内容不适用于python 3,因为.message不是ValueError的成员。相反,你可以使用这个(有效的python 2.6或更高版本或3.x):
try:
try:
raise ValueError
except ValueError as err:
if not err.args:
err.args=('',)
err.args = err.args + ("hello",)
raise
except ValueError as e:
print(" error was "+ str(type(e))+str(e.args))
Edit2:
根据目的,您还可以选择在自己的变量名下添加额外的信息。对于python2和python3:
try:
try:
raise ValueError
except ValueError as err:
err.extra_info = "hello"
raise
except ValueError as e:
print(" error was "+ str(type(e))+str(e))
if 'extra_info' in dir(e):
print e.extra_info
It seems all the answers are adding info to e.args[0], thereby altering the existing error message. Is there a downside to extending the args tuple instead? I think the possible upside is, you can leave the original error message alone for cases where parsing that string is needed; and you could add multiple elements to the tuple if your custom error handling produced several messages or error codes, for cases where the traceback would be parsed programmatically (like via a system monitoring tool).
## Approach #1, if the exception may not be derived from Exception and well-behaved:
def to_int(x):
try:
return int(x)
except Exception as e:
e.args = (e.args if e.args else tuple()) + ('Custom message',)
raise
>>> to_int('12')
12
>>> to_int('12 monkeys')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in to_int
ValueError: ("invalid literal for int() with base 10: '12 monkeys'", 'Custom message')
or
## Approach #2, if the exception is always derived from Exception and well-behaved:
def to_int(x):
try:
return int(x)
except Exception as e:
e.args += ('Custom message',)
raise
>>> to_int('12')
12
>>> to_int('12 monkeys')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in to_int
ValueError: ("invalid literal for int() with base 10: '12 monkeys'", 'Custom message')
你能看出这种方法的缺点吗?
当前的答案对我来说并不是很好,如果没有重新捕获异常,则不会显示附加的消息。
但是像下面这样做既保持跟踪,又显示附加的消息,不管是否重新捕获异常。
try:
raise ValueError("Original message")
except ValueError as err:
t, v, tb = sys.exc_info()
raise t, ValueError(err.message + " Appended Info"), tb
(我使用Python 2.7,在Python 3中没有尝试过)