how to handle "getaddrinfo failed"?
Hallo, i have problem. i use mechanize, python 2.7 to connect some sites (the code is not important right now) i have list of sites and i connect to them one by now. When it happens the site from my list doesn't exist i get error:
urllib2.URLError: [Errno 11004] getaddrinfo failed
I tried to handle it by doing this:
except mechanize.URLError, e:
result = str(e.reason)
or
except urllib2.URLError, e:
result = str(e.reason)
or even
except Exception, e:
开发者_高级运维 result = str(e)
But it just don't want to work.
How to solve this? When this error happens i just want to print something like "connection failed" and move to the next address on the list. How to catch this error by except?
Random guess but try:
import socket
try:
...
except socket.gaierror:
pass
socket.gaierror is the "[Errno 11004] getaddrinfo failed" error.
You can easily figure out the exception if you do
try:
...
except:
import sys
# prints `type(e), e` where `e` is the last exception
print sys.exc_info()[:2]
Just do
except urrlib2.URLError:
print "Connection failed"
continue # NOTE: This assumes this is in a loop. If not, substitute for return
Most Python libraries tell you the type of the exception in the error report, in this case urllib2.URLError, so that is indeed what you except for.
However, if except Exception: is not working for you, you've got more serious problems than a user inputting a bad web address (assuming this is not urllib2's fault).
加载中,请稍侯......
精彩评论