gpt4 book ai didi

Python 只打印引发异常的回溯

转载 作者:行者123 更新时间:2023-12-03 23:07:31 25 4
gpt4 key购买 nike

我在带有附加消息的 try-except 块中引发了一个新异常。因此不再需要原始异常回溯。有什么方法可以删除原始回溯并仅打印新引发异常的回溯?

示例代码(Python 3.6.10):

try:
10/0
except:
raise Exception('some error')

输出:
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
d:\xxx\main.py in
1 try:
----> 2 10/0
3 except:

ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

Exception Traceback (most recent call last)
d:\xxx\main.py in
2 10/0
3 except:
----> 4 raise Exception('some error')

Exception: some error

期望的输出:
---------------------------------------------------------------------------
Exception Traceback (most recent call last)
d:\xxx\main.py in
2 10/0
3 except:
----> 4 raise Exception('some error')

Exception: some error

最佳答案

I'm raising a new exception in try-except block with additional message. The original exception traceback is therefore not needed anymore.



您可以丢弃原始异常,但我会重新考虑该决定。在 Python 3 中添加异常原因和上下文的原因是关于原始异常和堆栈跟踪的信息很有用。我会明确地将原始异常标记为新异常的原因,这会稍微改变消息:
try:
1/0
except ZeroDivisionError as e:
raise Exception("Oh crud") from e

输出:
Traceback (most recent call last):
File "main.py", line 2, in <module>
1/0
ZeroDivisionError: division by zero

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "main.py", line 4, in <module>
raise Exception("Oh crud") from e
Exception: Oh crud

也就是说,如果你真的想抑制关于原始异常的信息,你可以使用 None作为新异常的原因:
try:
1/0
except ZeroDivisionError:
raise Exception("Oh crud") from None

输出:
Traceback (most recent call last):
File "main.py", line 4, in <module>
raise Exception("Oh crud") from None
Exception: Oh crud

关于Python 只打印引发异常的回溯,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61452022/

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