August 25th 2009

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.




You can subscribe to new posts via email or RSS.