Reputation: 1445
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.
Upvotes: 2
Views: 1578
Reputation: 395
From python docs:
try:
raise Exception('spam', 'eggs')
except Exception as inst:
print(type(inst)) # the exception instance
print(inst.args) # arguments stored in .args
print(inst) # __str__ allows args to be printed directly,
Will be print:
<type 'exceptions.Exception'>
('spam', 'eggs')
('spam', 'eggs')
Upvotes: 0
Reputation: 881523
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
Upvotes: 3