打印例外

Mat*_*o12 4 python printing exception

我正在编写一个捕获错误(或异常)的小脚本.但是当异常发生时,我希望获得所有信息,如Traceback,异常名称和异常消息.它也应该在没有捕获到异常的情况下起作用但是下面的代码不应该受到影响(id应该出现错误,但脚本不会停止工作).
例如:在以下代码中将抛出异常.如果发生这种情况(并且只有它发生)我想做"清理".

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
Run Code Online (Sandbox Code Playgroud)

我不打算使用记录器,因为脚本非常智能(不超过100行),它只会被我使用.

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

und*_*run 5

您将要使用traceback模块:

import traceback
try:
    raise Exception('what')
except Exception:
    print(traceback.format_exc())
Run Code Online (Sandbox Code Playgroud)