Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

What is the difference between 'except IOError as e:' and 'except IOError, e:'

753 views
Skip to first unread message

Peng Yu

unread,
Nov 17, 2009, 9:28:16 PM11/17/09
to pytho...@python.org
I don't see any different between the following code in terms of
output. Are they exactly the same ('as' v.s. ',')?

try:
raise IOError('IOError')
except IOError as e:
print e

try:
raise IOError('IOError')
except IOError, e:
print e

Steven D'Aprano

unread,
Nov 17, 2009, 9:38:36 PM11/17/09
to
On Tue, 17 Nov 2009 20:28:16 -0600, Peng Yu wrote:

> I don't see any different between the following code in terms of output.
> Are they exactly the same ('as' v.s. ',')?
>
> try:
> raise IOError('IOError')
> except IOError as e:
> print e

This is the preferred syntax. It is used in Python 2.6 and better. It is
a syntax error in Python 2.5 and older.


> try:
> raise IOError('IOError')
> except IOError, e:
> print e

This is the obsolete syntax, used in Python 2.5 and older.


--
Steven

MRAB

unread,
Nov 17, 2009, 9:52:44 PM11/17/09
to pytho...@python.org
Peng Yu wrote:
> I don't see any different between the following code in terms of
> output. Are they exactly the same ('as' v.s. ',')?
>
> try:
> raise IOError('IOError')
> except IOError as e:
> print e
>
> try:
> raise IOError('IOError')
> except IOError, e:
> print e

The second form is the old form. Later versions of Python introduced the
first form because it is less confusing.

If you wanted a single 'except' to catch 2 exceptions you would need to
write:

try:
...
except (IOError, OSError):
...

Sometimes people who are new to Python mistakenly write:

try:
...
except IOError, OSError:
...

thinking that that form will catch 2 exceptions, and they'll then be
puzzled when it doesn't work properly.

Marcus Gnaß

unread,
Nov 18, 2009, 4:27:10 AM11/18/09
to MRAB, pytho...@python.org
0 new messages