4

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

Matt3o12
  • 4,192
  • 6
  • 32
  • 47
  • 2
    Use google.. http://stackoverflow.com/questions/3702675/print-the-full-traceback-in-python-without-halting-the-program – Gricha Apr 27 '13 at 22:19
  • i'm assuming you mean it should "act as if the exception hadn't been" raised rather than caught ... because if it hadn't been caught you'd get your traceback printed for you right? – underrun Apr 27 '13 at 22:21
  • Not exectly: It should also act if the exception had not been (the error should be appeared) but the following code mustn't be affected by it. – Matt3o12 Apr 27 '13 at 22:27

2 Answers2

5

You'll want to use the traceback module:

import traceback
try:
    raise Exception('what')
except Exception:
    print(traceback.format_exc())
underrun
  • 6,713
  • 2
  • 41
  • 53
2

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
Eric
  • 95,302
  • 53
  • 242
  • 374
  • 2
    So you mean _"It should also act if the exception hadn't been __raised__."_? They're very different. – Eric Apr 27 '13 at 22:20
  • Edit: Not exectly: It should also act if the exception had not been (the error should be appeared) but the following code mustn't be affected by it. – Matt3o12 Apr 27 '13 at 22:21