newbie question about confusing exception handling in urllib

Discussion in 'Python' started by cabbar@gmail.com, Apr 9, 2013.

  1. Guest

    Hi,

    I have been using Java/Perl professionally for many years and have been trying to learn python3 recently. As my first program, I tried writing a classfor a small project, and I am having really hard time understanding exception handling in urllib and in python in general...
    Basically, what I want to do is very simple, try to fetch something "tryurllib.request.urlopen(request)", and:
    - If request times out or connection is reset, re-try n times
    - If it fails, return an error
    - If it works return the content.

    But, this simple requirement became a nightmare for me. I am really confused about how I should be checking this because:
    - When connection times out, I sometimes get URLException with "reason" field set to socket.timeout, and checking (isinstance(exception.reason, socket.timeout)) works fine
    - But sometimes I get socket.timeout exception directly, and it has no "reason" field, so above statement fails, since there is no reason field there.
    - Connection reset is a totally different exception
    - Not to mention, some exceptions have msg / reason / errno fields but some don't, so there is no way of knowing exception details unless you check them one by one. The only common thing I could was to find call __str__()?
    - Since, there are too many possible exceptions, you need to catch BaseException (I received URLError, socket.timeout, ConnectionRefusedError, ConnectionResetError, BadStatusLine, and none share a common parent). And, catching the top level exception is not a good thing.

    So, I ended up writing the following, but from everything I know, this looks really ugly and wrong???

    try:
    response = urllib.request.urlopen(request)
    content = response.read()
    except BaseException as ue:
    if (isinstance(ue, socket.timeout) or (hasattr(ue, "reason") and isinstance(ue.reason, socket.timeout)) or isinstance(ue, ConnectionResetError)):
    print("REQUEST TIMED OUT")

    or, something like:

    except:
    (a1,a2,a3) = sys.exc_info()
    errorString = a2.__str__()
    if ((errorString.find("Connection reset by peer") >= 0) or (errorString.find("error timed out") >= 0)):

    Am I missing something here? I mean, is this really how I should be doing it?

    Thanks.
    , Apr 9, 2013
    #1
    1. Advertising

  2. Peter Otten Guest

    wrote:

    > Hi,
    >
    > I have been using Java/Perl professionally for many years and have been
    > trying to learn python3 recently. As my first program, I tried writing a
    > class for a small project, and I am having really hard time understanding
    > exception handling in urllib and in python in general... Basically, what I
    > want to do is very simple, try to fetch something
    > "tryurllib.request.urlopen(request)", and:
    > - If request times out or connection is reset, re-try n times
    > - If it fails, return an error
    > - If it works return the content.
    >
    > But, this simple requirement became a nightmare for me. I am really
    > confused about how I should be checking this because:
    > - When connection times out, I sometimes get URLException with "reason"
    > field set to socket.timeout, and checking (isinstance(exception.reason,
    > socket.timeout)) works fine - But sometimes I get socket.timeout
    > exception directly, and it has no "reason" field, so above statement
    > fails, since there is no reason field there. - Connection reset is a
    > totally different exception - Not to mention, some exceptions have msg /
    > reason / errno fields but some don't, so there is no way of knowing
    > exception details unless you check them one by one. The only common
    > thing I could was to find call __str__()? - Since, there are too many
    > possible exceptions, you need to catch BaseException (I received
    > URLError, socket.timeout, ConnectionRefusedError, ConnectionResetError,
    > BadStatusLine, and none share a common parent). And, catching the top
    > level exception is not a good thing.
    >
    > So, I ended up writing the following, but from everything I know, this
    > looks really ugly and wrong???
    >
    > try:
    > response = urllib.request.urlopen(request)
    > content = response.read()
    > except BaseException as ue:
    > if (isinstance(ue, socket.timeout) or (hasattr(ue, "reason")
    > and isinstance(ue.reason, socket.timeout)) or isinstance(ue,
    > ConnectionResetError)):
    > print("REQUEST TIMED OUT")
    >
    > or, something like:
    >
    > except:
    > (a1,a2,a3) = sys.exc_info()
    > errorString = a2.__str__()
    > if ((errorString.find("Connection reset by peer") >= 0) or
    > (errorString.find("error timed out") >= 0)):
    >
    > Am I missing something here? I mean, is this really how I should be doing
    > it?


    Does it help if you reorganize your code a bit? For example:

    def read_content(request)
    try:
    response = urllib.request.urlopen(request)
    content = response.read()
    except socket.timeout:
    return None
    except URLError as ue:
    if isinstance(ue.reason, socket.timeout):
    return None
    raise
    return content

    for i in range(max_tries):
    content = read_content(request)
    if content is not None:
    break
    else:
    print("Could not download", request)

    Instead of returning an out-of-band response (None) you could also raise a
    custom exception (called MyTimeoutError below). The retry-loop would then
    become

    for i in range(max_tries):
    try:
    content = read_content(request):
    except MyTimeoutError:
    pass
    else:
    break
    else:
    print("Could not download", request)
    Peter Otten, Apr 9, 2013
    #2
    1. Advertising

  3. Guest

    Ah, looks better.

    But, 2 questions:

    1. I should also catch ConnectionResetError I am guessing.
    2. How do I handle all other exceptions, just say Exception: and handle them? I want to silently ignore them.

    Thanks...

    On Tuesday, April 9, 2013 2:41:51 PM UTC+3, wrote:
    > Hi,
    >
    >
    >
    > I have been using Java/Perl professionally for many years and have been trying to learn python3 recently. As my first program, I tried writing a class for a small project, and I am having really hard time understanding exception handling in urllib and in python in general...
    >
    > Basically, what I want to do is very simple, try to fetch something "tryurllib.request.urlopen(request)", and:
    >
    > - If request times out or connection is reset, re-try n times
    >
    > - If it fails, return an error
    >
    > - If it works return the content.
    >
    >
    >
    > But, this simple requirement became a nightmare for me. I am really confused about how I should be checking this because:
    >
    > - When connection times out, I sometimes get URLException with "reason"field set to socket.timeout, and checking (isinstance(exception.reason, socket.timeout)) works fine
    >
    > - But sometimes I get socket.timeout exception directly, and it has no "reason" field, so above statement fails, since there is no reason field there.
    >
    > - Connection reset is a totally different exception
    >
    > - Not to mention, some exceptions have msg / reason / errno fields but some don't, so there is no way of knowing exception details unless you check them one by one. The only common thing I could was to find call __str__()?
    >
    > - Since, there are too many possible exceptions, you need to catch BaseException (I received URLError, socket.timeout, ConnectionRefusedError, ConnectionResetError, BadStatusLine, and none share a common parent). And, catching the top level exception is not a good thing.
    >
    >
    >
    > So, I ended up writing the following, but from everything I know, this looks really ugly and wrong???
    >
    >
    >
    > try:
    >
    > response = urllib.request.urlopen(request)
    >
    > content = response.read()
    >
    > except BaseException as ue:
    >
    > if (isinstance(ue, socket.timeout) or (hasattr(ue, "reason") and isinstance(ue.reason, socket.timeout)) or isinstance(ue, ConnectionResetError)):
    >
    > print("REQUEST TIMED OUT")
    >
    >
    >
    > or, something like:
    >
    >
    >
    > except:
    >
    > (a1,a2,a3) = sys.exc_info()
    >
    > errorString = a2.__str__()
    >
    > if ((errorString.find("Connection reset by peer") >= 0) or (errorString.find("error timed out") >= 0)):
    >
    >
    >
    > Am I missing something here? I mean, is this really how I should be doingit?
    >
    >
    >
    > Thanks.
    , Apr 9, 2013
    #3
  4. On 4/9/2013 7:41 AM, wrote:
    > Hi,
    >
    > I have been using Java/Perl professionally for many years and have been trying to learn python3 recently. As my first program, I tried writing a class for a small project, and I am having really hard time understanding exception handling in urllib and in python in general...
    > Basically, what I want to do is very simple,


    Very funny ;-). What you are trying to do, as your first project, is
    interact with the large, multi-layered, non=deterministic monster known
    as Internet, with timeout handling, through multiple layers of library
    code. When it comes to exception handling, this is about the most
    complex thing you can do.

    > try to fetch something "tryurllib.request.urlopen(request)", and:
    > - If request times out or connection is reset, re-try n times
    > - If it fails, return an error
    > - If it works return the content.
    >
    > But, this simple requirement became a nightmare for me. I am really confused about how I should be checking this because:
    > - When connection times out, I sometimes get URLException with "reason" field set to socket.timeout, and checking (isinstance(exception.reason, socket.timeout)) works fine
    > - But sometimes I get socket.timeout exception directly, and it has no "reason" field, so above statement fails, since there is no reason field there.


    If you are curious why the different exceptions for seemingly the same
    problem, you can look at the printed traceback to see where the
    different exceptions come from. Either don't catch the exceptions,
    re-raise them, or explicitly grab the traceback (from exc_info, I believe)

    > - Connection reset is a totally different exception
    > - Not to mention, some exceptions have msg / reason / errno fields but some don't, so there is no way of knowing exception details unless you check them one by one. The only common thing I could was to find call __str__()?


    The system is probably a bit more ragged then it might be if completely
    re-designed from scratch.

    > - Since, there are too many possible exceptions, you need to catch BaseException (I received URLError, socket.timeout, ConnectionRefusedError, ConnectionResetError, BadStatusLine, and none share a common parent). And, catching the top level exception is not a good thing.


    You are right, catching BaseException is bad. In particular, it will
    catch KeyboardInterrupt from a user trying to stop the process. It is
    also unnecessary as all the exceptions you want to catch are derived
    from Exception, which itself is derived from BaseException.

    > So, I ended up writing the following, but from everything I know, this looks really ugly and wrong???
    >
    > try:
    > response = urllib.request.urlopen(request)
    > content = response.read()
    > except BaseException as ue:


    except Exception as ue:

    > if (isinstance(ue, socket.timeout) or (hasattr(ue, "reason") and isinstance(ue.reason, socket.timeout)) or isinstance(ue, ConnectionResetError)):
    > print("REQUEST TIMED OUT")
    >
    > or, something like:
    >
    > except:


    except Exception:

    > (a1,a2,a3) = sys.exc_info()
    > errorString = a2.__str__()
    > if ((errorString.find("Connection reset by peer") >= 0) or (errorString.find("error timed out") >= 0)):


    --
    Terry Jan Reedy
    Terry Jan Reedy, Apr 9, 2013
    #4
  5. On Tue, 09 Apr 2013 06:19:09 -0700, cabbar wrote:

    > How do I
    > handle all other exceptions, just say Exception: and handle them? I want
    > to silently ignore them.


    Please don't. That is normally poor practice, since it simply hides bugs
    in your code.

    As a general rule, you should only catch exceptions that you know are
    harmless, and that you can recover from. If you don't know that it's
    harmless, then it's probably a bug, and you should let it raise, so you
    can see the traceback and fix it. In the words of Chris Smith:

    "I find it amusing when novice programmers believe their
    main job is preventing programs from crashing. ... More
    experienced programmers realize that correct code is
    great, code that crashes could use improvement, but
    incorrect code that doesn’t crash is a horrible nightmare."


    One exception to this rule (no pun intended) is that sometimes you want
    to hide the details of unexpected tracebacks from your users. In that
    case, it may be acceptable to wrap your application's main function in a
    try block, catch any unexpected exceptions, log the exception, and then
    quietly exit with a short, non-threatening error message that won't scare
    the civilians:


    try:
    main()
    except Exception as err:
    log(err)
    print("Sorry, an unexpected error has occurred.")
    print("Please contact support for assistance.")
    sys.exit(-1)


    Still want to catch all unexpected errors, and ignore them? If you're
    absolutely sure that this is the right thing to do, then:

    try:
    code_goes_here()
    except Exception:
    pass

    But really, you shouldn't do this.

    (For experts only: you *probably* shouldn't do this.)



    --
    Steven
    Steven D'Aprano, Apr 9, 2013
    #5
  6. On Wed, Apr 10, 2013 at 1:05 AM, Steven D'Aprano
    <> wrote:
    > One exception to this rule (no pun intended) is that sometimes you want
    > to hide the details of unexpected tracebacks from your users. In that
    > case, it may be acceptable to wrap your application's main function in a
    > try block, catch any unexpected exceptions, log the exception, and then
    > quietly exit with a short, non-threatening error message that won't scare
    > the civilians


    This is important to some types of security concern, too; for
    instance, if I'm running a web server, I probably don't want to leak
    details of exceptions and tracebacks to a potential attacker. Same
    again: catch the exception, log it, return simple error message;
    additionally, you can return that message as an HTTP response rather
    than simply bombing the web server. But again, a bare except should
    almost always be logging its exceptions.

    True story, though not in Python: After taking over the code of an
    ex-coworker, I was trying to fix some crazy problems. Everything I did
    seemed to kinda-work, but nothing properly worked. Trying to clean up
    the code to comply with "use strict" mode (which will tell you what
    language this is, and it isn't Perl) was a matter of blundering about
    in the dark. Turned out there was an event handler somewhere that
    buried the *entire file full of code* behind a callback that caught
    and suppressed everything. Gee, thanks. Web browsers these days are
    pretty good at reporting exceptions - we were mainly using Chrome's
    inbuilt Firebug-equivalent - but our brilliant coworker saw fit to
    hide them all.

    Exceptions are a huge boon.

    ChrisA
    Chris Angelico, Apr 9, 2013
    #6
  7. Ian Kelly Guest

    On Tue, Apr 9, 2013 at 5:41 AM, <> wrote:
    > try:
    > response = urllib.request.urlopen(request)
    > content = response.read()
    > except BaseException as ue:
    > if (isinstance(ue, socket.timeout) or (hasattr(ue, "reason") and isinstance(ue.reason, socket.timeout)) or isinstance(ue, ConnectionResetError)):
    > print("REQUEST TIMED OUT")


    I'm surprised nobody has yet pointed out that you can catch multiple
    specific exception types in the except clause rather than needing to
    organize them under a catch-all base class. These two code blocks are
    basically equivalent:

    try:
    do_stuff()
    except BaseException as ue:
    if isinstance(ue, (socket.timeout, ConnectionResetError)):
    handle_it()
    else:
    raise

    try:
    do_stuff()
    except (socket.timeout, ConnectionResetError) as ue:
    handle_it()

    Cheers,
    Ian
    Ian Kelly, Apr 9, 2013
    #7
    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. Replies:
    3
    Views:
    265
  2. Jonathan Gardner

    Asynchronous urllib (urllib+asyncore)?

    Jonathan Gardner, Feb 26, 2008, in forum: Python
    Replies:
    1
    Views:
    470
    Terry Jones
    Feb 27, 2008
  3. Peter
    Replies:
    34
    Views:
    1,936
    James Kanze
    Oct 17, 2009
  4. Chris McDonald
    Replies:
    0
    Views:
    287
    Chris McDonald
    Nov 1, 2010
  5. Oltmans
    Replies:
    1
    Views:
    90
    Andreas Bergmaier
    Mar 21, 2011
Loading...

Share This Page