try... except with unknown error types

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Aug 19 22:13:57 CEST 2011


John Gordon wrote:

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

Good question.

If Python "doesn't recognize it as an error type name", there is a reason
for that. Exceptions are exactly the same as every other name:

>>> foo.spam
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined
>>> urllib2.HTTPError
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'urllib2' is not defined



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

Except that is nearly always poor advice, because it catches too much: it
hides bugs in code, as well as things which should be caught.

You should always catch the absolute minimum you need to catch.



-- 
Steven




More information about the Python-list mailing list