Reputation: 408
I am trying to understand if I can handle the following error in python.
So I have a program which repeatedly calls the following line:
candidate = urllib2.urlopen(absolute_path)
After running my program for some seconds, I turned off my wifi
connection, and got the following error:
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>
Is there any way I can handle this error?
Upvotes: 1
Views: 4064
Reputation: 1824
Depends what you want to do when you get this Exception. You can use try-except
, standard Python's exception handling technique.
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
Upvotes: 1