Issue
I want to try a statement and if there is an error, I want it to print the original error it receives, but also add my own statement to it.
I was looking for this answer, found something that was almost complete here.
The following code did almost all I wanted (I'm using Python 2 so it works):
except Exception, e:
print str(e)
This way I can print the error message and the string I wanted myself, however it does not print the error type (IOError
, NameError
, etc.). What I want is for it to print the exact same message it would normally do (so ErrorType: ErrorString
) plus my own statement.
Solution
If you want to print the exception information, you can use the traceback
module:
import traceback
try:
infinity = 1 / 0
except Exception as e:
print "PREAMBLE"
traceback.print_exc()
print "POSTAMBLE, I guess"
This gives you:
PREAMBLE
Traceback (most recent call last):
File "testprog.py", line 3, in <module>
infinity = 1 / 0
ZeroDivisionError: integer division or modulo by zero
POSTAMBLE, I guess
You can also rethrow the exception without traceback
but, since it's an exception being thrown, you can't do anything afterwards:
try:
infinity = 1 / 0
except Exception as e:
print "PREAMBLE"
raise
print "POSTAMBLE, I guess"
Note the lack of POSTAMBLE
in this case:
PREAMBLE
Traceback (most recent call last):
File "testprog.py", line 2, in <module>
infinity = 1 / 0
ZeroDivisionError: integer division or modulo by zero
Answered By - paxdiablo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.