在异常处理块中引发异常并抑制首次错误

12 投票
1 回答
4442 浏览
提问于 2025-04-18 11:05

我正在尝试捕捉一个错误,并在代码中的某个地方抛出一个更具体的错误:

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 个回答

18

在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
>>>

撰写回答