Python - urllib2 > how to escape HTTP errors
Question: I am making a python app and I want to read a file from the net. this is the
code that I am using to read it :

    
    
    urllib2.urlopen("http://example.com/check.txt").read()
    

everything works great but when I point it to a url that do not exist, it
gives HTTP 404: not found error and that is normal.

the problem is that the app is designed to work on windows, so, it will be
compiled. on windows, when the app tries to get a file from a url that do not
exist, the app crushes and gives an error window + it creates a log that
contains HTTP 404: NOT found error.

I tried to escape this error but I failed. This is the full code:

    
    
    import urllib2
    
    file = urllib2.urlopen("http://example.com/check.txt")
    
    try:
        file.read()
    except urllib2.URLError:
        print "File Not Found"
    
    else:
        print "File is found"
    

please, if you know how to escape this error, help me.


Answer: You should apply the try..except around the urlopen, not the read.

Try this

    
    
    import urllib2
    try:
        fh = urllib2.urlopen('http://example.com/check.txt')
        print fh.read()
    except urllib2.HTTPError, e:
        print e.code 
    except urllib2.URLError, e:
        print e.code
    

