Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #11869 > unrolled thread

Re: try... except with unknown error types

Started byYingjie Lin <Yingjie.Lin@mssm.edu>
First post2011-08-19 15:35 -0400
Last post2011-08-19 15:35 -0400
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: try... except with unknown error types Yingjie Lin <Yingjie.Lin@mssm.edu> - 2011-08-19 15:35 -0400

#11869 — Re: try... except with unknown error types

FromYingjie Lin <Yingjie.Lin@mssm.edu>
Date2011-08-19 15:35 -0400
SubjectRe: try... except with unknown error types
Message-ID<mailman.234.1313782560.27778.python-list@python.org>
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.

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web