python - 打印异常

标签 python exception printing

我正在编写一个捕获错误(或异常)的小脚本。但是当异常发生时,我想获得所有信息,如回溯、异常名称和异常消息。如果未捕获到异常但不应影响以下代码,它也应该采取行动(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/

相关文章:

python - numpy.disutils.system_info.NotFoundError : no lapack/blas resources found

python - 如何从重命名脚本中提取 PDF 文档的标题?

java - try catch Java 中的无限循环

java - 如何在 BigDecimal (Java) 中存储无穷大?

css - 如何在 IE/FF 中添加用于打印的背景图像?

javascript - 从 chrome 打印对话框中禁用打印选项

python - 属性错误: 'builtin_function_or_method' object has no attribute 'randint'

python - 如何在保留 UTF-8 字母的同时进行 slugify

csv - 在Databricks中,检查路径是否存在

c# - 在显示 PrintDialog 后修改 PrinterSettings