除块外引发异常并抑制第一个错误

时间:2014-06-25 20:19:22

标签: python python-3.x exception-handling

我试图捕获异常并在我的代码中的某个位置引发更具体的错误:

try:
  something_crazy()
except SomeReallyVagueError:
  raise ABetterError('message')

这适用于Python 2,但在Python 3中,它显示了两个例外:

Traceback(most recent call last):
...
SomeReallyVagueError: ...
...

During handling of the above exception, another exception occurred:

Traceback(most recent call last):
...
ABetterError: message
...

有没有办法解决这个问题,以至于SomeReallyVagueError的追溯没有显示?

1 个答案:

答案 0 :(得分:14)

在Python 3.3及更高版本中,您可以使用raise <exception> from None语法来抑制第一个异常的回溯:

>>> try:
...     1/0
... except ZeroDivisionError:
...     raise ValueError
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
ValueError
>>>
>>>
>>> try:
...     1/0
... except ZeroDivisionError:
...     raise ValueError from None
...
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
ValueError
>>>