Nova
Nova

Reputation: 2666

Why can't I break out of a loop when catching StopIteration?

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

Answers (1)

Nova
Nova

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

Related Questions