Bwire Bwire - 1 month ago 8
Python Question

Python exception syntax difference?

I am just being curious about the syntax of python exceptions as I can't seem to understand when you are suppossed to use the syntax below to catch an exception.

try:
"""
Code that can raise an exception...
"""
except Exception as e:
pass


and

try:
"""
Code that can raise an exception...
"""
except Exception, e:
pass


What is the difference?

Answer

Note: As Martijn points out, comma variable form is deprecated in Python 3.x. So, its always better to use as form.

As per http://docs.python.org/2/tutorial/errors.html#handling-exceptions

except Exception, e:

is equivalent to

except Exception as e:

Commas are still used when you are catching multiple exceptions at once, like this

except (NameError, ValueError) as e:

Remember, the parentheses around the exceptions are mandatory when catching multiple exceptions.

Comments