throw() and close()
throw() injects an exception into a generator at the yield point. close() raises GeneratorExit to terminate it cleanly.
throw() injects an exception into a generator at the yield point. close() raises GeneratorExit to terminate it cleanly.
def safe_gen():
try:
while True:
yield
except GeneratorExit:
print("Generator closed")
finally:
print("Cleanup done")
g = safe_gen()
next(g)
g.close() # "Generator closed" then "Cleanup done"
Use finally in generators for cleanup — it runs on close() as well.