不要在异常堆栈中显示 Python raise-line [英] Don't show Python raise-line in the exception stack

查看:25
本文介绍了不要在异常堆栈中显示 Python raise-line的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在 Python 库中引发自己的异常时,异常堆栈将引发行本身显示为堆栈的最后一项.这显然不是错误,在概念上是正确的,但将重点放在了在外部使用代码(例如作为模块)时对调试无用的东西.

When I raise my owns exceptions in my Python libraries, the exception stack shows the raise-line itself as the last item of the stack. This is obviously not an error, is conceptually right, but points the focus on something that is not useful for debugging when you're are using code externally, for example as a module.

有没有办法避免这种情况并强制 Python 将前一个到最后一个堆栈项显示为最后一个,就像标准 Python 库一样.

Is there a way to avoid this and force Python to show the previous-to-last stack item as the last one, like the standard Python libraries.

推荐答案

适当的警告:修改解释器的行为通常是不受欢迎的.在任何情况下,准确查看错误发生的位置可能有助于调试,尤其是在函数可能因多种不同原因引发错误的情况下.

Due warning: modifying the behaviour of the interpreter is generally frowned upon. And in any case, seeing exactly where an error was raised may be helpful in debugging, especially if a function can raise an error for several different reasons.

如果您使用 traceback 模块,并替换sys.excepthook 使用自定义函数,可能可以做到这一点.但是进行更改会影响整个程序的错误显示,而不仅仅是您的模块,因此可能不建议这样做.

If you use the traceback module, and replace sys.excepthook with a custom function, it's probably possible to do this. But making the change will affect error display for the entire program, not just your module, so is probably not recommended.

您还可以考虑将代码放在 try/except 块中,然后修改错误并重新引发它.但是,您最好将时间花在避免意外错误上,并为可能出现的错误编写信息丰富的错误消息.

You could also look at putting code in try/except blocks, then modifying the error and re-raising it. But your time is probably better spent making unexpected errors unlikely, and writing informative error messages for those that could arise.

这篇关于不要在异常堆栈中显示 Python raise-line的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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