Posted by: John Bresnahan | December 12, 2012

When except Exception does not work…

I recently ran into a situation where my catch all exception handler was not trapping an exception. I had the following

try:
    ....
except Exception, ex:
    log("bad things happened")
    raise

Bad things did happen, but I never got the log message. However, if I did this:

try:
    ....
except Exception, ex:
    log("bad things happened")
    raise
except:
    log("Why am I here?")

I did get the log message “Why am I here?”. The reason for this is that python allows you to raise two things as exceptions.

  1. Classes which are derived from Exception. These are trapped in the first handler
  2. Old style classes which are derived from nothing. These are not children of Exception so they are trapped in the second handler.

The following code snip illustrates this:

class OldError:
    pass

try:
    raise OldError()
except Exception, ex:
    print "This will not happen"
except:
    print "This will"
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: