urllib2 and exceptions

Chris Rebert clp at rebertia.com
Sun Sep 28 15:11:58 EDT 2008


On Sun, Sep 28, 2008 at 11:03 AM, robean <st1999 at gmail.com> wrote:
> 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
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

My Python begs to differ:

#tmp.py
import urllib2

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

try:
    handle = urllib2.urlopen(url)

except urllib2.HTTPError, e:
    print "There was an http error"
    print e

except urllib2.URLError, e:
    print "There is a problem with the URL"
    print e

except urllib2.IOError, e:
    print "You have an IOError"
    print e

#in the shell
$ python -V
Python 2.5.1
$ python Desktop/tmp.py
There was an http error
HTTP Error 404: Not Found

Are you using an outdated version of Python perhaps?

Regards,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com



More information about the Python-list mailing list