Handle Arbitrary Exception, Print Default Exception Message

Viewed 10366

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 an 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?

5 Answers
try:
    #stuff
except Exception as e:
    print e

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

Source Errors and Exceptions

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.

while True:
    try:
        # Do your stuff
    except Exception, e:
        print "Something happened: %s" % e
Related