urllib2.URLError异常没有被抓住

时间:2014-06-22 03:03:37

标签: python http urllib2

我有以下代码块:

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

运行时有时会导致服务器抛出urllib2.URLError: <urlopen error [Errno 104] Connection reset by peer>。但是这个例外没有被except块捕获:

  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>

导致异常未被捕获的原因是什么?提前谢谢!

1 个答案:

答案 0 :(得分:1)

它似乎被抓住了:

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

注意代码示例末尾的raise函数。如果您的if语句的计算结果为False,则会重新引发相同的异常,这似乎很可能就是这种情况。尝试将raise替换为print("IF STATEMENT FALSE")以查看此内容。