96

In python, there are two ways to catch an exception

except Exception, e:

except Exception as e:

It seems like 'as e' is the one to use going forward. In what version of python did this change? Any idea why?

Nathan
  • 4,545
  • 6
  • 32
  • 49
  • 16
    The `as e` syntax was introduced in Python 2.6. – Wooble Feb 25 '11 at 16:30
  • 3
    Just a note for anyone using Jython, who reads this and decides to replace all "Exception, e" with "Exception as e": it's not supported yet, as of Jython 2.5.2. See: http://stackoverflow.com/questions/3020966/jython-syntaxerror – Cam Jackson Aug 08 '11 at 06:59

3 Answers3

50

This PEP introduces changes intended to help eliminate ambiguities in Python's grammar, simplify exception classes, simplify garbage collection for exceptions and reduce the size of the language in Python 3.0.

PEP 3110: "Catching Exceptions in Python 3000"

Magnus Hoff
  • 21,529
  • 9
  • 63
  • 82
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • But I'm using 2.6 and I have a access to both styles. My coworker had to change by code to `except Exception, e` instead of `except Exception as e` because (stuck) he's using an older version. – Nathan Feb 25 '11 at 17:53
  • 3
    The new grammar was backported to 2.6, but the old grammar was not removed. – Ignacio Vazquez-Abrams Feb 25 '11 at 17:55
16

Short answer for the why: Exception, e and Exception, TypeError are hard to tell apart. Long answer: what Ignacio said.

nmichaels
  • 49,466
  • 12
  • 107
  • 135
14

The first proposal for using the "as" is here: http://mail.python.org/pipermail/python-dev/2006-March/062449.html. They thought it would be more intuitive to read the code

Fábio Diniz
  • 10,077
  • 3
  • 38
  • 45