GeneratorExit
GeneratorExit
Traceback
Traceback (most recent call last):
File "main.py", line 6, in <module>
yield "done" # RuntimeError: generator ignored GeneratorExit
GeneratorExitWhat causes this error
A generator's close() method was called (either explicitly or by garbage collection), which throws GeneratorExit into the generator to allow cleanup.
How to fix it
Use try/finally in generators for cleanup code. If you catch GeneratorExit, do not yield after catching it — either return or re-raise. For resource management, prefer context managers.
Code that causes this error
def gen():
try:
while True:
yield
except GeneratorExit:
yield "done" # RuntimeError: generator ignored GeneratorExitFixed code
def gen():
try:
while True:
yield
finally:
print("Cleaning up")
g = gen()
next(g)
g.close() # prints "Cleaning up"About GeneratorExit
GeneratorExit is raised inside a generator when the generator's `.close()` method is called, or when the generator is garbage collected. This gives the generator an opportunity to perform cleanup — for example, closing file handles or releasing resources in a finally block. GeneratorExit inherits from BaseException (not Exception) so that a bare `except Exception` clause does not accidentally catch it.
If a generator catches GeneratorExit and then yields another value (instead of finishing or re-raising), Python raises a RuntimeError. In normal code, you rarely see GeneratorExit explicitly; it is part of the generator protocol and is handled automatically. You may encounter it when writing context managers using generators (`@contextmanager`) or when implementing custom cleanup logic in generators that manage resources.
Common scenarios
Infinite recursion from missing or incorrect base cases
Modifying dictionaries or sets during iteration
Calling generators or coroutines in unsupported ways
Using asyncio event loops incorrectly or attempting to nest them