Reputation: 2666
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?
Upvotes: 1
Views: 446
Reputation: 2666
It turns out StopIteration
is actually a subclass of Exception
, not just another throwable class. So the StopIteration
handler was never called since StopIteration
is alrady handled by the one for Exception
. I just had to put the StopIteration
handler on top:
it = iter(xrange(5))
while True:
try:
num = it.next()
print(num)
except StopIteration:
break
except Exception as e:
print(e) # log and ignore
print('finished')
Upvotes: 2