14

I am developing a Django site and have been having trouble trying to work out the best way to do exception handling. I have been doing

try:
    Some code
except:
    log error in my own words, i.e 'Some code' failed to execute
    Some other code

This catches all exceptions thus ensuring my site does not deliver 500 errors and such like. But, with my limited knowledge I am losing the actual exception and it is making it a real pain to debug. How do I print the error that occured? Currently I comment out try: catch: and see the error and fix it. There must be a better way!

Thanks in advance

Rich

3
  • 2
    Where have you seen the "naked" except statement like that? Can you provide a quote or a link to a tutorial which shows this kind of programming? It's considered to be a bad practice. I want to know where you learned this. Commented Jan 4, 2011 at 11:21
  • 6
    @S.Lott: Instead of coming down on someone like that it might be better to offer some alternative approach and explain why it is considered bad practice. Commented Nov 3, 2011 at 10:28
  • @magiconair, I feel S.Lott is doing the Right Thing and is criticizing a tutorial author rather than OP. I have personally seen colleagues attempt to get "bare except" through code review multiple times, and I always educate them about the ugly consequences of ignoring KeyboardInterrupt, so the PR is improved prior to a merge. Commented Oct 18, 2022 at 1:35

5 Answers 5

25

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

Comments

5
#!/usr/bin/env python

import sys

try:
    0 / 0
except Exception, e:
    print >> sys.stderr, 'Hello %s' % e
    # Hello integer division or modulo by zero

Note that you can catch multiple exceptions for one block, e.g.:

try:
    open(filename)
except NameError, e:
    print >> sys.stderr, e
except IOError, ioe:
    print >> sys.stderr, ioe

More on exception handling can be found in this tutorial:

Comments

3

this can help

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 printed directly
    x, y = inst.args
    print 'x =', x
    print 'y =', y

Comments

1

Django Middleware is how you process exceptions in Django sites.

To catch all exceptions, you have to create a Django middleware and create a process_exception method.

from django.http import HttpResponse

class SomeMiddleware(object):
    def process_exception(self, request, exception):
        'Intercept exceptions'

        return HttpResponse('Hey! an error occurred',
                content_type='text/plain')

then you add it to your MIDDLEWARE_CLASSES setting:

MIDDLEWARE_CLASSES = (
    # ...
    'some.module.SomeMiddleware',
)

Then you get control over what to do when encountering any kind of exception.

I think this answered your question. But you're probably better off overriding the 500.html template or the handler500 view. Notice that these views don't come into play until you set DEBUG to False in your project settings.

Comments

1

Try this:

try:
  # some code
except Exception, e:
  # log error with data from e

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.