在追溯中提高异常而没有“raise”? [英] Raising exceptions without 'raise' in the traceback?

查看:173
本文介绍了在追溯中提高异常而没有“raise”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

不要在异常堆栈中显示Python raise行

内置异常,如 NameError 等,给我一个跟踪异常发生的代码。我正在开发一个实用程序模块,它会让我知道,如果使用我的模块的代码引发异常,则异常是我的引发WhateverError 之前的追溯中的最后一个事件。

Built in exceptions like NameError etc. give me a traceback to the point in my code where the exception occurred. I'm working on a utility module and it bugs me that if code using my module raises and exception the last thing in the traceback before the exception is my raise WhateverError.

有没有办法在python中引发异常,并让tracback停止一帧内置异常(不需要编写c代码)?

Is there any way to raise an exception in python and have the tracback stop one frame up ala the builtin exceptions (without writing c code)?

推荐答案

纯Python不提供一种突破现有回溯对象或创建任意追溯对象的方法。

Pure Python doesn't provide a way to mutate existing traceback objects or create arbitrary traceback objects.

>>> 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在实用程序模块中验证错误的能力。

Note that if it were possible to do this you wouldn't just affect the default formatting of tracebacks, you'd also interfere with people's ability to use pdb to post-mortem errors in your utility module.

如果您的实用程序模块正在记录或者以其他方式格式化回溯,那么您只能不包括您认为不感兴趣的输出框架。例如,标准库的 unittest 模块在报告运行测试时发生的错误时执行此操作。

If the traceback is being logged or otherwise formatted by your utility module then you can just not include the frames you consider uninteresting in the output. For instance, the standard library's unittest module does this when reporting errors that occur while running tests.

这篇关于在追溯中提高异常而没有“raise”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆