try... except with unknown error types

Yingjie Lin Yingjie.Lin at mssm.edu
Fri Aug 19 21:35:56 CEST 2011


Hi Zero,

I see! This is very helpful. Thank you.

- Yingjie







On Aug 19, 2011, at 3:30 PM, Zero Piraeus wrote:

> :
> 
> On 19 August 2011 15:09, Yingjie Lin <Yingjie.Lin at mssm.edu> wrote:
>> 
>> I have been using try...except statements in the situations where I can expect a certain type of errors might occur.
>> But  sometimes I don't exactly know the possible error types, or sometimes I just can't "spell" the error types correctly.
>> For example,
>> 
>> 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.
>> 
>> 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 should always specify the error type, so that your error-handling
> code won't attempt to handle an error it didn't anticipate and cause
> even more problems.
> 
> In this case, I think it's just that you haven't imported HTTPError
> into your namespace - if you do, it works:
> 
>>>> from urllib2 import urlopen, HTTPError
>>>> try:
> ...   response = urlopen("http://google.com/invalid")
> ... except HTTPError:
> ...   print "URL does not exist!"
> ...
> URL does not exist!
>>>> 
> 
> Alternatively:
> 
>>>> import urllib2
>>>> try:
> ...   response = urllib2.urlopen("http://google.com/invalid")
> ... except urllib2.HTTPError:
> ...   print "URL does not exist!"
> ...
> URL does not exist!
>>>> 
> 
> A careful look at the difference between these two ought to make it
> clear what's going on.
> 
> -[]z.




More information about the Python-list mailing list