On Sat, Sep 10, 2011 at 1:36 PM, Terry Reedy <tjre...@udel.edu> wrote:
> The statement containing the explicit next(items) call can optionally be
> wrapped to explicitly handle the case of an empty iterable in whatever
> manner is desired.
>
> try:
>    <set up with next(items)>
> except StopIteration:
>    raise ValueError("iterable cannot be empty")

The only time that's optional is when you're writing an iterator and
the try-except would end up looking like this:

try:
    # do stuff with next(items)
except StopIteration:
    raise StopIteration

And even then, it's probably a good idea to clearly document that
you're allowing a StopIteration from one iterator to propagate up as a
StopIteration for another.

Apart from that case, whenever you call next() you should always be
prepared to catch a StopIteration.  Letting a StopIteration propagate
up the stack to parts unknown is bad juju because it's a flow control
exception, not an error-signaling exception.  If it happens to
propagate up to another for loop, then it will break out of the for
loop, and the exception will simply be swallowed.

Cheers,
Ian
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to