【问题标题】:Raising exceptions without 'raise' in the traceback? [duplicate]在回溯中引发没有“引发”的异常? [复制]
【发布时间】:2011-06-20 11:59:09
【问题描述】:

可能重复:
Don't show Python raise-line in the exception stack

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

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

【问题讨论】:

    标签: python exception raise


    【解决方案1】:

    纯 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 模块在报告运行测试时发生的错误时会这样做。

    【讨论】:

      猜你喜欢
      • 2021-12-26
      • 1970-01-01
      • 2014-06-02
      • 1970-01-01
      • 1970-01-01
      • 2021-07-09
      • 1970-01-01
      • 2016-11-30
      • 1970-01-01
      相关资源
      最近更新 更多