views:

240

answers:

4

I have a program, a part of which executes a loop. During the execution of this loop, there are exceptions. Obviously, I would like my program to run without errors, but for the sake of progress, I would like the program to execute over the entire input and not stop when an exception is thrown. The easiest way to do this would be by implementing and except block.

However, when I do this, it excepts all exceptions and continues with the program and I never get to see the exception message (which I need in order to debug).

Is there a way to except any arbitrary exception and be able to print out the exception message in the except block?

+3  A: 
try:
    #stuff
except Exception, e:
    print e

The traceback module provides various functions for extracting more information from the exception object (e, above).

Autopulated
+2  A: 
while True:
    try:
        # Do your stuff
    except Exception, e:
        print "Something happened: %s" % e
Ned Batchelder
+7  A: 

Consider using the Python logging module, this is will give you a lot of the functionality to log problems for later inspection. Below is a simple example of using the logging module to to log exceptions:

import logging
LOG_FILE = '/tmp/exceptions.log'
logging.basicConfig(filename=LOG_FILE,level=logging.ERROR)

while True:
try:
    # Code that may throw exceptions
except Exception, e:
    logging.exception("An exception happened")

By using the logging.exception function within an exception handler as is done here the Exception info is automatically added to the logging message.

Tendayi Mawushe
+1  A: 

I find this to be much more useful for debugging:

from traceback import print_exc
try:
    raise Exception("doh!")
except:
    print_exc()
Matt Joiner