Python 只打印引发异常的回溯

Gab*_*Gab 5 python exception raise

我在 try- except 块中引发了一个带有附加消息的新异常。因此不再需要原来的异常回溯。有没有办法删除原始的回溯并只打印新引发的异常的回溯?

示例代码(Python 3.6.10):

try:
    10/0
except:
    raise Exception('some error')
Run Code Online (Sandbox Code Playgroud)

输出:

---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
d:\xxx\main.py in 
      1 try:
----> 2     10/0
      3 except:

ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

Exception                                 Traceback (most recent call last)
d:\xxx\main.py in 
      2     10/0
      3 except:
----> 4     raise Exception('some error')

Exception: some error
Run Code Online (Sandbox Code Playgroud)

期望的输出:

---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
d:\xxx\main.py in 
      2     10/0
      3 except:
----> 4     raise Exception('some error')

Exception: some error
Run Code Online (Sandbox Code Playgroud)

use*_*ica 5

我在 try- except 块中引发了一个带有附加消息的新异常。因此不再需要原来的异常回溯。

您可以放弃原来的例外,但我会重新考虑该决定。Python 3 中添加异常原因和上下文的原因是因为有关原始异常和堆栈跟踪的信息非常有用。我明确地将原始异常标记为新异常的原因,这稍微改变了消息:

try:
    1/0
except ZeroDivisionError as e:
    raise Exception("Oh crud") from e
Run Code Online (Sandbox Code Playgroud)

输出:

Traceback (most recent call last):
  File "main.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 "main.py", line 4, in <module>
    raise Exception("Oh crud") from e
Exception: Oh crud
Run Code Online (Sandbox Code Playgroud)

也就是说,如果您确实想抑制有关原始异常的信息,可以使用None作为新异常的原因:

try:
    1/0
except ZeroDivisionError:
    raise Exception("Oh crud") from None
Run Code Online (Sandbox Code Playgroud)

输出:

Traceback (most recent call last):
  File "main.py", line 4, in <module>
    raise Exception("Oh crud") from None
Exception: Oh crud
Run Code Online (Sandbox Code Playgroud)