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

MRAB python at mrabarnett.plus.com
Wed Nov 18 03:52:44 CET 2009


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.



More information about the Python-list mailing list