pmohandas
pmohandas

Reputation: 3819

urllib2.URLError exception not getting caught

I have the following code block:

def bar( self ):
    ...
    try:
        response = urllib2.urlopen(req).read()
    except urllib2.URLError, e:
        if (e.errno == errno.ECONNRESET and retryCount < MAX_RETRY_COUNT):
            time.sleep( 10 )
            self.bar()
        else:
            raise

Which when run may sometimes result in the server throwing a urllib2.URLError: <urlopen error [Errno 104] Connection reset by peer>. But this exception is not getting caught by the except block:

  File "/tmp/foo.py", line 123, in bar
    response = urllib2.urlopen(req).read()
  File "/usr/local/lib/python2.7/urllib2.py", line 127, in urlopen
    return _opener.open(url, data, timeout)
  File "/usr/local/lib/python2.7/urllib2.py", line 404, in open
    response = self._open(req, data)
  File "/usr/local/lib/python2.7/urllib2.py", line 422, in _open
    '_open', req)
  File "/usr/local/lib/python2.7/urllib2.py", line 382, in _call_chain
    result = func(*args)
  File "/usr/local/lib/python2.7/urllib2.py", line 1222, in https_open
    return self.do_open(httplib.HTTPSConnection, req)
  File "/usr/local/lib/python2.7/urllib2.py", line 1184, in do_open
    raise URLError(err)
urllib2.URLError: <urlopen error [Errno 104] Connection reset by peer>

What is causing the exception to not get caught? Thanks in advance!

Upvotes: 0

Views: 523

Answers (1)

Martin Konecny
Martin Konecny

Reputation: 59601

It appears it is getting caught:

try:
    response = urllib2.urlopen(req).read()
except urllib2.URLError, e:
    if (e.errno == errno.ECONNRESET and retryCount < MAX_RETRY_COUNT):
        time.sleep( 10 )
        self.bar()
    else:
        raise

Notice the raise function at the end of the code sample. This will re-raise the same exception if your if statement evaluates to False, which appears to be very likely the case. Try replacing raise with print("IF STATEMENT FALSE") to see this.

Upvotes: 1

Related Questions