gpt4 book ai didi

python - 如果不立即重新引发异常回溯,则隐藏

转载 作者:IT老高 更新时间:2023-10-28 21:41:16 26 4
gpt4 key购买 nike

我有一段类似这样的代码:

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 引发异常时,我收到以下回溯:

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

从这里我看不出异常来自哪里。原始回溯丢失。

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

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引发最后一个异常。

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

如果你使用 raise something Python 无法知道 something 是刚刚捕获的异常,还是带有新堆栈跟踪的新异常。这就是保留堆栈跟踪的空白 raise 的原因。

Reference here

关于python - 如果不立即重新引发异常回溯,则隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4825234/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com