try... except with unknown error types

John Gordon gordon at panix.com
Fri Aug 19 15:14:54 EDT 2011


In <mailman.230.1313780957.27778.python-list at python.org> Yingjie Lin <Yingjie.Lin at mssm.edu> writes:

> 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.

Have you imported urllib2 in your code?

> 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 catch all exceptions by catching the base class Exception:

  try:
    some_method()
  except Exception, e:
    print "some error happened, here is the explanation:"
    print str(e)

-- 
John Gordon                   A is for Amy, who fell down the stairs
gordon at panix.com              B is for Basil, assaulted by bears
                                -- Edward Gorey, "The Gashlycrumb Tinies"




More information about the Python-list mailing list