【问题标题】:Printing an exception打印异常
【发布时间】:2013-04-27 22:16:06
【问题描述】:

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

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

【问题讨论】:

  • 我假设你的意思是它应该“表现得好像没有发生异常”而不是被捕获......因为如果它没有被捕获,你会得到你的回溯打印你说对了吗?
  • 不完全:如果没有出现异常(应该出现错误),它也应该起作用,但下面的代码一定不受它的影响。

标签: python exception printing


【解决方案1】:

你会想要使用回溯模块:

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

【讨论】:

    【解决方案2】:

    你可以解决:

    如果异常没有被捕获,它也应该采取行动。

    try:
        1 / 0
    except Exception as e: 
        do_cleanup(e)
        raise
    

    【讨论】:

    • 所以你的意思是“如果没有引发异常,它也应该起作用。”?它们非常不同。
    • 编辑:不完全是:如果没有出现异常(应该出现错误),它也应该起作用,但下面的代码不能受它的影响。
    猜你喜欢
    • 1970-01-01
    • 2017-12-21
    • 1970-01-01
    • 1970-01-01
    • 2015-05-04
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多