Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print error type, error statement and own statement

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.

like image 978
RobinAugy Avatar asked May 14 '26 21:05

RobinAugy


1 Answers

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
like image 149
paxdiablo Avatar answered May 17 '26 11:05

paxdiablo