Python中的URLError

时间:2014-09-26 14:33:03

标签: python exception exception-handling error-handling

我试图理解我是否可以在python中处理以下错误。

所以我有一个程序,它反复调用以下行:

candidate = urllib2.urlopen(absolute_path)

运行我的程序几秒后,我关闭了wifi连接,并收到以下错误:

File "crawler.py", line 28, in urlQuery
  candidate = urllib2.urlopen(absolute_path)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 127, in urlopen
  return _opener.open(url, data, timeout)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 404, in open
  response = self._open(req, data)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 422, in _open
'_open', req)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 382, in _call_chain
  result = func(*args)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1214, in http_open
  return self.do_open(httplib.HTTPConnection, req)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1184, in do_open
  raise URLError(err)
urllib2.URLError: <urlopen error [Errno 65] No route to host>

有什么方法可以处理这个错误吗?

1 个答案:

答案 0 :(得分:1)

当您收到此异常时,取决于您要执行的操作。您可以使用try-except标准Python的异常处理技术。

try:
    candidate = urllib2.urlopen(absolute_path)
#except Exception as e: # catches any exception
except urllib2.URLError as e: # catches urllib2.URLError in e
    print ('WiFi connection perhaps lost !! Trying one more time...')
    try:
        candidate = urllib2.urlopen(absolute_path)
    except:
        print ('WiFi connection really lost !! Bailing out..')
        print (e) # print outs the exception message