Re: question about try/except blocks

Discussion in 'Python' started by Devin Jeanpierre, May 3, 2013.

  1. On Thu, May 2, 2013 at 9:54 PM, J <> wrote:
    > Would it be better to wrap the call and catch the OSError there, or
    > wrap the whole with open() block in the function itself?
    >
    > My thought is to wrap the with open() call in the function so that I'm
    > not wrapping the function call every time I use the class somewhere,
    > but then I am not sure of that as it leads to nested try blocks like
    > so:


    It definitely shouldn't be done that way, since you might catch
    exceptions in other circumstances too. Try this:

    try:
    f = open(dest, 'wb', 0)
    except OSError as exc:
    ...
    with f:
    try:
    ...
    except IOError as exc:
    ...
    else:
    ...

    -- Devin

    > try:
    > with open(dest, 'wb', 0) as outfile:
    > try:
    > stuff
    > except IOError as exec:
    > more stuff
    > else:
    > other stuff
    > except OSError as exc:
    > error handling stuff
    > return False
    >
    >
    > I think, functionally, that should work, but should nested try/except
    > blocks be avoided?
    Devin Jeanpierre, May 3, 2013
    #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. John Salerno
    Replies:
    20
    Views:
    843
    John Salerno
    Aug 11, 2006
  2. Fabio Z Tessitore

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

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

    try -> except -> else -> except?

    David House, Jul 6, 2009, in forum: Python
    Replies:
    2
    Views:
    332
    Bruno Desthuilliers
    Jul 6, 2009
  4. matt
    Replies:
    1
    Views:
    255
    George Ogata
    Aug 6, 2004
  5. J
    Replies:
    1
    Views:
    195
    Steven D'Aprano
    May 3, 2013
Loading...

Share This Page