generators and exceptions

Dimitris Garanatsios dg96057 at
Sun Mar 16 02:46:16 CET 2003

Clark C. Evans wrote:
> Hello, I'm playing with 2.2 generators, and it seems
> that they don't like exceptions...
> <code>
> Anyway, this _only_ prints out 4, instead of 4, 2
> as I expected.  I expect 4, 2 beacuse an equivalent
> iterator would produce 4, 2. <...>

To which particular "equivalent iterator" are you refering to and why is 
it supposed to produce "4, 2"? One of us is propably missing something 
Anyway, i don't see a way to yield a value of 2 from this example.

> <...> It seems that generators
> die on the first exception... <...>

Actually, the exception is never raised. Using a print statement instead 
of pass in the try...except block will verify this. The reason is that 
the second call to the next() method continues execution just after the 
yield statement, which was responsible for the printed value 4. Then it 
sets val = -1 and goes for the second loop which exits immediately 
raising a StopIteration exception (again, a print statement reveals 
that). After that, we reach to the end.

I suspect though, that "val =- 1" is a typoed "val = 1", in which case 
the exception will get raised without causing any problems to your 
generator ;-)

> <...> is there a way around 
> this? <...>

Sneeze carefully! :-)

         /   /   \   \
        (  _|     |_  )
         \/  \___/  \/
Sometimes, solution is under your nose...
Sneeze carefully and blow with caution!

More information about the Python-list mailing list