[Tutor] Unable to catch exception

Kent Johnson kent37 at tds.net
Sun Aug 10 19:54:41 CEST 2008

On Sat, Aug 9, 2008 at 12:28 PM, James <jtp at nc.rr.com> wrote:
> All,
> I'm having a rather strange problem that I'm hoping someone can shed
> some light on. I'm trying to catch a BadStatusLine exception raised by
> the httplib library.
> The error only happens once every blue moon, but to avoid a crash I
> setup a try/catch.
> try:
>   <download page code here>
> catch BadStatusLine:
>   print "yuck!"
> However, somehow the thread that this code is in still raised a
> BadStatusLine exception and the thread stopped cold.

How did you import BadStatusLine?

One strange gotcha about except statements is that the except clause
is not evaluated until an exception is raised, so you can have an
invalid name and you won't know it. For example this runs fine, even
though foo is not defined:
In [1]: try:
   ...:     1
   ...: except foo:
   ...:     pass
Out[1]: 1

OTOH if an exception is raised it causes a NameError:
In [2]: try:
   ...:     1/0
   ...: except foo:
   ...:     pass
<type 'exceptions.NameError'>             Traceback (most recent call last)

/Users/kent/<ipython console> in <module>()

<type 'exceptions.NameError'>: name 'foo' is not defined


More information about the Tutor mailing list