Welcome, guest | Sign In | My Account | Store | Cart

Traps exceptions - to be printed or displayed without actually raising the exception.

Sometimes useful to get the full error message from an exception - this code captures it as text - to be displayed, saved or whatever.

Python, 14 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
from StringIO import StringIO
from traceback import print_exc

try:
   raise Exception

except Exception, e:
    f=StringIO()      # this creates a file object
    print_exc(file=f)
    error_mess = f.getvalue().splitlines()
    print "Damn... Exception Occurred :\n"
    for line in error_mess:
        print line
    dummy = raw_input('Hit Enter........ ') 

I wanted to trap exceptions in a text parsing program (that would parse many files). The code would fail if the text was badly formed - I needed the error displayed for debugging the text file - but for the code to continue to the next file.

This code displays the full text of the exception (as normal). The example shown here can also be used when creating console programs for windows.

It displays the error and then waits for the user to hit enter before vanishing - so you can see the full text of the error.

This was actually shown to me by one of the kind fellows on help@python.org