Exception handling vs. hasNext()

Yuh-Ruey Chen maian330 at gmail.com
Sat Nov 17 01:14:55 PST 2007

More advantages to StopIteration:

1) There are some iterations in which calculating whether the next
iteration exists is non-trivial, such as iterating on trees.

2) While one could work around non-trivial hasNext() calculations by
"pre-advancing" the iterator, i.e. if an iterator has returned the i-th
item, it has already calculated the (i+1)-th item, making hasNext()
simply check if the (i+1)-th item exists, such an approach is not only
less efficient, but won't work if the iterator makes side effects.

3) Repeated hasNext() checks can be slower than throwing and catching a
StopIteration, especially if the compiler is optimized to expect that
StopIteration from an iterator.

4) Iterator-generators hide the messy business of StopIteration:

// range is an iterator-generator (note the yield statement)
function range(len) {
    for (let i = 0; i < len; ++i)
       yield i;

for (let x in range(10))

No mention of StopIteration - or even next() - anywhere in that code yet
|range(10)| is clearly an iterator.

In case you were wondering, ES4's iteration protocol is heavily inspired
from Python, and I think Python has handled this iteration business very

-Yuh-Ruey Chen

Erik Arvidsson wrote:
> One benefit of StopIteration is that code inside map/some/every etc
> can just throw a StopIteration to stop the iteration.  The same thing
> is harder to keep clean with a hasNext/next pattern.

More information about the Es4-discuss mailing list