newbie question about confusing exception handling in urllib

C

cabbar

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.
 
P

Peter Otten

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)
 
C

cabbar

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...
 
T

Terry Jan Reedy

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:
 
S

Steven D'Aprano

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.)
 
C

Chris Angelico

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
 
I

Ian Kelly

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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top