bug with exception handling or subtle bug on my end?

Peter Otten __peter__ at web.de
Thu Dec 18 13:10:54 EST 2003


Chris Green wrote:

> I'm encountering a place where if I use a for loop I can't catch
> the error raised by a member.
> 
> I've tested python 2.3 and 2.3.1 ( the only ones I had quickly around
> ) and it's still occuring.  Any insight would be appreciated but I
> can't figure out why the stand alone call works but for i in doesn't.
> 
> I can work around this for now but if someone could please explain
> this behavior, it's driving me crazy. I've tried catching everything I
> could think of.. Thanks!
> 

The reason for this strange behaviour boils down to the following:

SyntaxError: invalid syntax
>>> def t():
...     raise Exception, "so what"
...     for i in range(3):
...             yield i
...
>>> x = t()
>>> x.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 2, in t
Exception: so what
>>>

I. e., an exception from inside a generator (and ConfigParser.items() is
such a biest) is only thrown on the first invocation of its next() method
which is implicitly done by the for loop. So you cannot catch the exception
because it is just not raised inside the getNetworkConfig() method.
I would consider this behaviour a bug in ConfigParser.
As a workaround, you can do (both untested):

    def getNetworkConfig(self):
        if self.has_section("Network"):
            return self.items("Network")
        else:
            return []

or

    def getNetworkConfig(self):
        try:
            return list(self.items("Network"))
        except ConfigParser.NoSectionError:
            return []

Peter




More information about the Python-list mailing list