Fix Python – Python try…except comma vs ‘as’ in except

Question

Asked By – Peter Graham

What is the difference between ‘,’ and ‘as’ in except statements, eg:

try:
    pass
except Exception, exception:
    pass

and:

try:
    pass
except Exception as exception:
    pass

Is the second syntax legal in 2.6? It works in CPython 2.6 on Windows but the 2.5 interpreter in cygwin complains that it is invalid.

If they are both valid in 2.6 which should I use?

Now we will see solution for issue: Python try…except comma vs ‘as’ in except


Answer

The definitive document is PEP-3110: Catching Exceptions

Summary:

  • In Python 3.x, using as is required to assign an exception to a variable.
  • In Python 2.6+, use the as syntax, since it is far less ambiguous and forward compatible with Python 3.x.
  • In Python 2.5 and earlier, use the comma version, since as isn’t supported.

This question is answered By – Amber

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0