Python 仅打印引发异常的回溯

Python only print traceback of raised exception

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

示例代码(Python 3.6.10):

try:
    10/0
except:
    raise Exception('some error')

输出:

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

期望的输出:

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

Exception: some error

使用with_traceback

import sys, traceback
try:
    10/0
except Exception as exc:
    raise  exc.with_traceback(None)
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-31-d77f0aded0d7> in <module>()
      3     10/0
      4 except Exception as exc:
----> 5     raise  exc.with_traceback(None)

ZeroDivisionError: division by zero

如果你只是想展示一下:

import sys, traceback
try:
    10/0
except Exception:
    ex_type, ex, tb = sys.exc_info()
    traceback.print_tb(tb)
File "<ipython-input-4-1283199eb169>", line 3, in <module>
    10/0

备选方案

import sys, traceback
try:
    10/0
except Exception as exc:
    tb_str = traceback.format_exception(etype=type(exc), value=exc, tb=exc.__traceback__)
    for i in tb_str: print(i)
Traceback (most recent call last):

  File "<ipython-input-17-3bc95dc2ebf5>", line 3, in <module>
    10/0

ZeroDivisionError: division by zero

I'm raising a new exception in try-except block with additional message. The original exception traceback is therefore not needed anymore.

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

try:
    1/0
except ZeroDivisionError as e:
    raise Exception("Oh crud") from e

输出:

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

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

try:
    1/0
except ZeroDivisionError:
    raise Exception("Oh crud") from None

输出:

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