4

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?

SilentGhost
  • 307,395
  • 66
  • 306
  • 293
RogerZ
  • 61
  • 1
  • 2
  • 3

2 Answers2

10

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]
Jochen Ritzel
  • 104,512
  • 31
  • 200
  • 194
3

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).

new123456
  • 873
  • 1
  • 12
  • 21
  • 1
    Old post, I know, but for any others who come across it, `urrlib2.URLError` is misspelt. It should be `urllib2.URLError` for Py2 (and `urllib.error.URLError` in Py3). – David Metcalfe Jan 29 '17 at 00:49