On 8/19/11 12:09 PM, Yingjie Lin wrote:
> try:
>       response = urlopen(urljoin(uri1, uri2))
> except urllib2.HTTPError:
>       print "URL does not exist!"
> 
> Though "urllib2.HTTPError" is the error type reported by Python, Python 
> doesn't recognize it as an error type name. 
> I tried using "HTTPError" alone too, but that's not recognized either.

Exceptions are objects like any other, and they are defined in specific
places. Only the standard ones are available everywhere; things like
IndexError and AttributeError. See the 'exceptions' module for the
standard ones. Everything else, you have to 'grab' the object from where
it lives -- in this case, in urllib2.


> Does anyone know what error type I should put after the except statement? or 
> even better: is there a way not to specify
> the error types? Thank you.

You can use a "bare except", like so:

   try:
       ...
   except:
       ...

But avoid it, if you can. Or at least, don't let it become
habit-forming: for networking code and interaction with external things,
I usually have a bare-except as a final fallback, after trying other
more specific things-- but only as a last resort.

FWIW, the error hierarchy of url fetching is more then a little bit
annoying. My own _request object I end up using for one of our services
catches, in order:

  try:
      ...
  except urllib2.HTTPError:
  except urllib2.URLError:
  except httplib.BadStatusLine:
  except httplib.HTTPException:
  except socket.timeout:
  except:


With each case logging and handling the error in a bit of a different
way. (Though most, eventually, resulting in the request being retried --
all in the name of a mandate that this particular bit of code must not,
under any circumstances, not ultimately work. Even going so far as to
start having hour long waits between retries until the  other side is
finally up :P)


-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/

Attachment: signature.asc
Description: OpenPGP digital signature

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to