Chris Lamb

No-one expects the string literal exception

Every Python programmer knows that:

try:
    # .. code ..
except:
    print "Caught exception"

is semantically equivalent to:

try:
    # .. code ..
except Exception, e:
    print "Caught exception"

Or is it? Bam:

try:
    raise "No-one expects the string literal exception"
except Exception, e:
    print "Oops, didn't catch this exception"

You'll actually need Python >= 2.5 to reproduce that behaviour, but what's actually neat about all this is that the exception will be caught—without warnings—as you originally expected under Python 2.6, dispite string literals being "truly and utterly dead". See if you can work out why.


Chris Lamb is a freelance software developer and the current Debian Project Leader. You can read other posts by me, see software I have written or read more about me. You can also follow me @lolamby.


Tags: GNU/Linux Hacks

Planets: ALUG UWCS WUGLUG Debian

Tuesday 25th August 2009


Six comments