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


Groups > comp.lang.python > #11868

Re: try... except with unknown error types

References <58958843-AE74-44BB-B5E3-96D7A37D779E@mssm.edu>
Date 2011-08-19 15:30 -0400
Subject Re: try... except with unknown error types
From Zero Piraeus <schesis@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.233.1313782258.27778.python-list@python.org> (permalink)

Show all headers | View raw


:

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


Thread

Re: try... except with unknown error types Zero Piraeus <schesis@gmail.com> - 2011-08-19 15:30 -0400

csiph-web