Python PSA: Use "as", Not "," To Name Caught Exception Instances

, Wellesley, MA

A public service announcement for Python coders:

Python lets you catch SomeException and assign it to a variable e like so:

try:
    ...
except SomeException, e:
    ...

Regrettably, it will behave similarly if you do this:

try:
    ...
except SomeException, SomeOtherException:
    ...

And then very bad things(tm) will happen when you try to dereference SomeOtherException later, since, much to your surprise, it will refer to an instance of SomeException rather than the original class named SomeOtherException.

So don’t use that syntax. Instead, write your except clauses like one of the following:

except SomeException:
except SomeException as e:
except (SomeException, SomeOtherException):
except (SomeException, SomeOtherException) as e:

Python 3 will force you to remember, but as long as you’re using Python 2 it’s your burden to bear.

Enjoyed reading this post? Discuss it on Reddit, or follow me on Twitter.