如果不立即重新提出异常追溯隐藏 [英] Exception traceback is hidden if not re-raised immediately

查看:134
本文介绍了如果不立即重新提出异常追溯隐藏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段类似于以下代码:

I've got a piece of code similar to this:

import sys

def func1():
    func2()

def func2():
    raise Exception('test error')

def main():
    err = None

    try:
        func1()
    except:
        err = sys.exc_info()[1]
        pass

    # some extra processing, involving checking err details (if err is not None)

    # need to re-raise err so caller can do its own handling
    if err:
        raise err

if __name__ == '__main__':
    main()

func2 引发异常时,我收到以下追溯:

When func2 raises an exception I receive the following traceback:

Traceback (most recent call last):
  File "err_test.py", line 25, in <module>
    main()
  File "err_test.py", line 22, in main
    raise err
Exception: test error

从这里我看不到异常来自哪里。原来的追溯丢失。

From here I don't see where the exception is coming from. The original traceback is lost.

如何保留原始的追溯并重新提升?我想看到类似的东西:

How can I preserve original traceback and re-raise it? I want to see something similar to this:

Traceback (most recent call last):
  File "err_test.py", line 26, in <module>
    main()
  File "err_test.py", line 13, in main
    func1()
  File "err_test.py", line 4, in func1
    func2()
  File "err_test.py", line 7, in func2
    raise Exception('test error')
Exception: test error


推荐答案

空白 raise 引发最后一个异常。 / p>

A blank raise raises the last exception.

# need to re-raise err so caller can do its own handling
if err:
    raise

如果你使用提出一些东西 Python没有办法知道如果某些东西是以前遇到的异常,或者是新的堆栈跟踪的异常。这就是为什么有一个空白的 raise 来保留堆栈跟踪。

If you use raise something Python has no way of knowing if something was an exception just caught before, or a new exception with a new stack trace. That's why there is the blank raise that preserves the stack trace.

此处参考

这篇关于如果不立即重新提出异常追溯隐藏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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