catch specific HTTP error in python

Arnab Sen Gupta picture Arnab Sen Gupta · Jul 7, 2010 · Viewed 110.3k times · Source

I want to catch a specific http error and not any one of the entire family.. what I was trying to do is --

import urllib2
try:
   urllib2.urlopen("some url")
except urllib2.HTTPError:
   <whatever>

but what I end up is catching any kind of http error, but I want to catch only if the specified webpage doesn't exist!! probably that's HTTP error 404..but I don't know how to specify that catch only error 404 and let the system run the default handler for other events..ny suggestions??

Answer

Tim Pietzcker picture Tim Pietzcker · Jul 7, 2010

Python 3

from urllib.error import HTTPError

Python 2

from urllib2 import HTTPError

Just catch HTTPError, handle it, and if it's not Error 404, simply use raise to re-raise the exception.

See the Python tutorial.

e.g. complete example for Pyhton 2

import urllib2
from urllib2 import HTTPError
try:
   urllib2.urlopen("some url")
except HTTPError as err:
   if err.code == 404:
       <whatever>
   else:
       raise