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

Discussion in 'Python' started by MRAB, Nov 18, 2009.

  1. MRAB

    MRAB Guest

    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.
     
    MRAB, Nov 18, 2009
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. jakk
    Replies:
    4
    Views:
    12,491
  2. John Salerno
    Replies:
    20
    Views:
    869
    John Salerno
    Aug 11, 2006
  3. Fabio Z Tessitore

    who is simpler? try/except/else or try/except

    Fabio Z Tessitore, Aug 12, 2007, in forum: Python
    Replies:
    5
    Views:
    389
  4. David House

    try -> except -> else -> except?

    David House, Jul 6, 2009, in forum: Python
    Replies:
    2
    Views:
    356
    Bruno Desthuilliers
    Jul 6, 2009
  5. Peng Yu
    Replies:
    1
    Views:
    546
    Steven D'Aprano
    Nov 18, 2009
Loading...

Share This Page