Why do iterators in Python raise an exception?
- by NullUserException
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?