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

kir*_*sos 9 python exception-handling python-3.x

我正在尝试捕获异常并在我的代码中的某个点引发更具体的错误:

try:
  something_crazy()
except SomeReallyVagueError:
  raise ABetterError('message')
Run Code Online (Sandbox Code Playgroud)

这适用于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
...
Run Code Online (Sandbox Code Playgroud)

有没有办法绕过这个,所以SomeReallyVagueError没有显示回溯?

iCo*_*dez 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
>>>
Run Code Online (Sandbox Code Playgroud)