I need to catch exceptions thrown by next(it) so I can’t use a regular for loop in this case. So I wrote this code:
it = iter(xrange(5))
while True:
try:
num = it.next()
print(num)
except Exception as e:
print(e) # log and ignore
except StopIteration:
break
print('finished')
This doesn’t work, after the numbers are exhausted I get an infinite loop. What am I doing wrong?
It turns out
StopIterationis actually a subclass ofException, not just another throwable class. So theStopIterationhandler was never called sinceStopIterationis alrady handled by the one forException. I just had to put theStopIterationhandler on top: