Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing an exception

I'm writing a little script which catches an error (or exception). But when the exception occurs I want to have all information like the Traceback, exception name and exception message. It should also act if the exception hadn't been caught but the following code shouldn't be affected (i.d the error should be appear but script doesn't stop working).
For example: in the following code a exception will be thrown. If that happens (and only if it happens) I want to make "cleanup".

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

I'm not going to use a logger because the script is very smart (no longer than 100 lines) and it will only be used by me.

Edit: I'm using python 2.x

like image 810
Matt3o12 Avatar asked Mar 24 '23 04:03

Matt3o12


2 Answers

You'll want to use the traceback module:

import traceback
try:
    raise Exception('what')
except Exception:
    print(traceback.format_exc())
like image 132
underrun Avatar answered Apr 06 '23 00:04

underrun


You can solve:

It should also act if the exception hadn't been caught.

with

try:
    1 / 0
except Exception as e: 
    do_cleanup(e)
    raise
like image 22
Eric Avatar answered Apr 05 '23 23:04

Eric