如何用Python中的自定义消息引发相同的异常?

2024-10-02 16:32:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码中有这个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)

Tags: 代码anthatmyasexceptiondosomething
3条回答
try:
    try:
        int('a')
    except ValueError as e:
        raise ValueError('There is a problem: {0}'.format(e))
except ValueError as err:
    print err

印刷品:

There is a problem: invalid literal for int() with base 10: 'a'

更新:对于Python 3,请选中Ben's answer


要将消息附加到当前异常并重新引发它,请执行以下操作: (外部尝试/例外只是为了显示效果)

对于python 2.x,其中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]


编辑:@Ducan points在注释中,由于.message不是ValueError的成员,以上内容不适用于python 3。相反,您可以使用它(有效的Python2.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))

编辑2:

根据用途,您还可以选择在自己的变量名下添加额外信息。对于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

我意识到这个问题已经出现了一段时间,但是一旦你足够幸运地只支持Python3.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

请注意,底部异常仅具有引发异常的stacktrace。调用方仍然可以通过访问它们捕获的异常的__cause__属性来获取原始异常。

带回溯

或者你可以使用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

请注意,底部的异常有执行无效除法的行和重新引发异常的行。

相关问题 更多 >