urllib2 and exceptions

robean st1999 at gmail.com
Sun Sep 28 14:03:34 EDT 2008


Hi everyone,

I have a question about using urllib2.

I like urllib2 better than urllib at least in part because it has more
elaborate support for handling errors: there is built in support for
URLError (for faulty urls) and HTTPError (for http errors that might
originate from, say, passing an invalid stock-ticker in the program
below).  However I can get neither to work.  I'm attaching below the
(very short) code: can anyone point out what I'm doing wrong?

Now, if I replace the URLError and HTTPError with IOError (the class
from which both URLError and HTTPError inherit), the program works
fine. Why is it that I can call the generic IOError class, but none of
the Error classes derived from that? These are clearly defined in the
urllib2 manual. Very confused...

Here's the code:


import urllib2

# read stock information from yahoo finance for Traget (TGT)
goodTicker = 'TGT' # program works with this
badTicker = 'TGTttttttt' # python doesn't understand either HTTPError
or URLError with this

url = "http://ichart.finance.yahoo.com/table.csv?s=" + badTicker

try:
        handle = urllib2.urlopen(url)

# this does not work
except HTTPError, e:
        print "There was an http error"
        print e

# this also does not work
except URLError, e:
        print "There is a problem with the URL"
        print e
        exit(1)

#this works
except IOError, e:
        print "You have an IOError"
        print e

text = handle.readlines()[:20]
for line in text:
        print line




More information about the Python-list mailing list