Python GeneratorExit Exception
Example
Find out when a generator is closed:
def numbers():
try:
yield 1
yield 2
except GeneratorExit:
print("The generator was closed")
gen = numbers()
print(next(gen))
gen.close()
Try it Yourself »
Definition and Usage
The GeneratorExit exception is raised inside a generator when the generator is closed with the close() method.
It is not an error. It gives the generator a chance to clean up, for example to close a file. A generator that catches GeneratorExit must not return any more values with yield.
GeneratorExit does not inherit from Exception, so except Exception does not catch it.
Related Pages
Read more about handling errors in our Python Try Except Tutorial.