如何使用Python中的自定义消息提升相同的异常? [英] How do I raise the same Exception with a custom message in Python?
问题描述
我的代码中有 try
block
I have this try
block in my code:
try:
do_something_that_might_raise_an_exception()
except ValueError as err:
errmsg = 'My custom error message.'
raise ValueError(errmsg)
严格来说,我其实是提高另一个 ValueError
,而不是 ValueError
由 do_something ...()
抛出,被称为 err
在这种情况下。如何将自定义消息附加到 err
?我尝试以下代码,但由于 err
,一个 ValueError
实例,而不是可调用:
Strictly speaking, I am actually raising another ValueError
, not the ValueError
thrown by do_something...()
, which is referred to as err
in this case. How do I attach a custom message to err
? I try the following code but fails due to err
, a ValueError
instance, not being callable:
try:
do_something_that_might_raise_an_exception()
except ValueError as err:
errmsg = 'My custom error message.'
raise err(errmsg)
推荐答案
更新:对于Python 3,请检查Ben的答案
附加消息到当前异常并重新提高它:
(外部尝试/除外仅仅是为了显示效果)
To attach a message to the current exception and re-raise it: (the outer try/except is just to show the effect)
对于python 2.x其中x > = 6:
For python 2.x where 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
。例如 err.problematic_array = [1,2,3]
。
Note that you can add whatever you like to err
. For example err.problematic_array=[1,2,3]
.
编辑: @Ducan指出上述内容不适用于python 3,因为 .message
不是<$ c的成员$ C> ValueError异常。相反,你可以使用这个(有效的python 2.6或更高版本或3.x):
@Ducan points in a comment the above does not work with python 3 since .message
is not a member of ValueError
. Instead you could use this (valid python 2.6 or later or 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:
Depending on what the purpose is, you can also opt for adding the extra information under your own variable name. For both python2 and 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
这篇关于如何使用Python中的自定义消息提升相同的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!