3

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.

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

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!
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?
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')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.