Errors and Exceptions – Python

Making the timeout error in urllib2 look a bit nicer.

The error

Sometimes when you’re trying to open a url and the connection is crap, it will fail to connect and Python will spit out a timeout error message…which looks a bit like this.

File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/", line 126, in urlopen
    return, data, timeout)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/", line 400, in open
    response = self._open(req, data)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/", line 418, in _open
    '_open', req)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/", line 378, in _call_chain
    result = func(*args)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/", line 1207, in http_open
    return self.do_open(httplib.HTTPConnection, req)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/", line 1177, in do_open
    raise URLError(err)
urllib2.URLError: <urlopen error [Errno 60] Operation timed out>

Using try: and except:

A nice way of removing this horrible message is by creating your own, using try: and except:. More info here.

That very last line of the original error message, the one with the 'urllib2.URLError', is very important as this will be used to state which error we are interested in for the exception.

So if you have a nice little bit of code like this…

from urllib2 import urlopen

# this is the site I want
str_the_url = ''

# open and read the site
str_site_html = urlopen(str_the_url).read()

Adding a couple of lines will improve the whole experience…

from urllib2 import urlopen

# this is the site I want
str_the_url = ''

# try to open and read the site...
    str_site_html = urlopen(str_the_url).read()

# if you can't do it, and the error you get
# is "urllib2.URLError" then do something else...
# in this case, print a message.
except urllib2.URLError:
    print 'Oops! Timeout Error! Sorry!'


Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s