Python Programming - Generators - Discussion

Discussion Forum : Generators - General Questions (Q.No. 61)
61.
How does the generator.throw(StopIteration) method affect a running generator?
It stops the generator and raises a StopIteration exception
It continues the generator's execution
It restarts the generator from the beginning
It has no effect on the running generator
Answer: Option
Explanation:
generator.throw(StopIteration) stops the generator and raises a StopIteration exception. However, using raise StopIteration directly is preferred.
def my_generator():
    try:
        while True:
            yield 1
    except StopIteration:
        print("Generator stopped")

gen = my_generator()
next(gen)
gen.throw(StopIteration)
Discussion:
Be the first person to comment on this question !

Post your comments here:

Your comments will be displayed after verification.