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
You'll want to use the traceback module:
import traceback
try:
raise Exception('what')
except Exception:
print(traceback.format_exc())
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With