7

可能重复:
不在异常堆栈中显示 Python raise-line

内置的异常NameError等让我回溯到我的代码中发生异常的点。我正在开发一个实用程序模块,如果使用我的模块的代码引发和异常,那么在异常之前的回溯中的最后一件事就是我的raise WhateverError.

有什么方法可以在 python 中引发异常并让回溯停止一帧 ala 内置异常(不编写 c 代码)?

4

1 回答 1

3

纯 Python 不提供改变现有回溯对象或创建任意回溯对象的方法。

>>> exc_info[2].tb_next = None
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: readonly attribute

>>> types.TracebackType()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot create 'traceback' instances

请注意,如果可以这样做,您不仅会影响回溯的默认格式,还会干扰人们使用 pdb 对实用程序模块中的错误进行事后分析的能力。

如果您的实用程序模块正在记录回溯或以其他方式格式化回溯,那么您不能在输出中包含您认为不感兴趣的帧。例如,标准库的unittest模块在报告运行测试时发生的错误时会这样做。

于 2011-06-20T12:44:35.563 回答