Exception handling in Python 3.x
John Nagle
nagle at animats.com
Mon Dec 6 15:53:47 EST 2010
On 12/3/2010 5:04 AM, Steven D'Aprano wrote:
> Consider the following common exception handling idiom:
>
> def func(iterable):
> it = iter(iterable)
> try:
> x = next(it)
> except StopIteration:
> raise ValueError("can't process empty iterable")
> print(x)
>
> The intention is:
>
> * detect an empty iterator by catching StopIteration;
> * if the iterator is empty, raise a ValueError;
> * otherwise process the iterator.
>
> Note that StopIteration is an internal detail of no relevance whatsoever
> to the caller. Expose this is unnecessary at best and confusing at worst.
Right. You're not entitled to assume that StopIteration is
how a generator exits. That's a CPyton thing; generators were
a retrofit, and that's how they were hacked in. Other implementations
may do generators differently.
John Nagle
More information about the Python-list
mailing list