Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #11869
| Date | 2011-08-19 15:35 -0400 |
|---|---|
| From | Yingjie Lin <Yingjie.Lin@mssm.edu> |
| Subject | Re: try... except with unknown error types |
| References | <58958843-AE74-44BB-B5E3-96D7A37D779E@mssm.edu> <CANaSqUfEO45ZE098VrFuOp1=bE1_Bcdk0wBtV2gP8AWNMcdbvA@mail.gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.234.1313782560.27778.python-list@python.org> (permalink) |
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@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.
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: try... except with unknown error types Yingjie Lin <Yingjie.Lin@mssm.edu> - 2011-08-19 15:35 -0400
csiph-web