python exception handling

You catch the exception in an exception variable:

try:
    # some code
except Exception, e:
    # Log the exception.

There are various ways to format the exception, the logging module (which I assume you/Django uses) has support to format exceptions, and the exceptions themselves usually render useful messages when rendered to strings.

Here is an example:

import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug('This message should go to the log file')

try:    
    1/0
except Exception as e:
    logging.exception(e)

This example uses the new “as” syntax to catch the exception, supported in Python 2.6 and later. The output of the above is:

DEBUG:root:This message should go to the log file
ERROR:root:integer division or modulo by zero
Traceback (most recent call last):
  File "untitled-1.py", line 6, in <module>
    1/0
ZeroDivisionError: integer division or modulo by zero

Leave a Comment