关于python:在except块中引发异常并抑制第一个错误

Raise exception in except block and suppress first error

本问题已经有最佳答案,请猛点这里访问。

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

1
2
3
4
try:
  something_crazy()
except SomeReallyVagueError:
  raise ABetterError('message')

这在python 2中有效,但在python 3中,它显示了两个异常:

1
2
3
4
5
6
7
8
9
10
11
Traceback(most recent call last):
...
SomeReallyVagueError: ...
...

During handling of the above exception, another exception occurred:

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

有没有办法解决这个问题,所以没有显示SomeReallyVagueError的回溯?


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
>>> 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
>>>