Why do iterators in Python raise an exception?

Posted by NullUserException on Programmers See other posts from Programmers or by NullUserException
Published on 2011-10-05T02:03:14Z Indexed on 2012/10/28 5:23 UTC
Read the original article Hit count: 375

Here's the syntax for iterators in Java (somewhat similar syntax in C#):

Iterator it = sequence.iterator();

while (it.hasNext()) {
    System.out.println(it.next());
}

Which makes sense. Here's the equivalent syntax in Python:

it = iter(sequence)
while True:
    try:
        value = it.next() 
    except StopIteration:
        break
    print(value)

I thought Exceptions were supposed to be used only in, well, exceptional circumstances.

Why does Python use exceptions to stop iteration?

© Programmers or respective owner

Related posts about python

Related posts about language-design