gpt4 book ai didi

python - 打印异常

转载 作者:太空狗 更新时间:2023-10-30 02:21:26 25 4
gpt4 key购买 nike

我正在编写一个捕获错误(或异常)的小脚本。但是当异常发生时,我想获得所有信息,如回溯、异常名称和异常消息。如果未捕获到异常但不应影响以下代码,它也应该采取行动(i.d 错误应该出现但脚本不会停止工作)。
例如:在下面的代码中会抛出一个异常。如果发生这种情况(并且仅当发生这种情况)我想进行“清理”。

try:
1 / 0
except Exception as e:
# Printing the Exception like it would have been done if the exception hadn't been caught:
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# ZeroDivisionError: integer division or modulo by zero
# With the traceback, the exception name and the exception message.

# Doing some additional stuff.
pass

我不会使用记录器,因为该脚本非常智能(不超过 100 行)并且它只会被我使用。

编辑:我正在使用 python 2.x

最佳答案

您需要使用回溯模块:

import traceback
try:
raise Exception('what')
except Exception:
print(traceback.format_exc())

关于python - 打印异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16257422/

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