How to handle "getaddrinfo failed"?

Hi, I have a problem. I am using mechanize, python 2.7 to connect some sites (the code does not matter right now) I have a list of sites and I am connecting to them one by one. When this happens, the site from my list does not exist, I get an error:

urllib2.URLError: [Errno 11004] getaddrinfo failed

I tried to handle this by doing the following:

             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 he just does not want to work.

How to solve this? When this error occurs, I just want to print something like "connection failed" and go to the next address in the list. How to catch this error with except?

+3
source share
2 answers

, :

import socket

try:
   ...
except socket.gaierror:
   pass

socket.gaierror "[Errno 11004] getaddrinfo failed".

,

try:
    ...
except:
    import sys
    # prints `type(e), e` where `e` is the last exception
    print sys.exc_info()[:2]
+6

except urrlib2.URLError:
    print "Connection failed"
    continue # NOTE: This assumes this is in a loop. If not, substitute for return

Python , urllib2.URLError, , except .

, except Exception: , , , - ( , urllib2).

+2

Source: https://habr.com/ru/post/1788836/


All Articles