1

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.

Community
  • 1
  • 1
RobinAugy
  • 1,159
  • 1
  • 9
  • 15

2 Answers2

3

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
paxdiablo
  • 772,407
  • 210
  • 1,477
  • 1,841
  • Ah, that is even easier indeed. I think my ideal scenario would be if I can print my own statement behind the error message, since it is more readable this way. But I also figured that when raising, you can't do anything after. So unless there is an easy way to extract the whole error message (including traceback) I think your answer is the best I can do :) Thanks! – RobinAugy Apr 22 '15 at 08:56
  • Just a note though: Since you are now not using the error string 'e' in your except clause, can't you just change "except Exception as e:" to "except:" now? – RobinAugy Apr 22 '15 at 08:56
0

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')
oxana
  • 365
  • 3
  • 9