SyntaxStudy
Sign Up
Python Advanced 4 min read

throw() and close()

throw() and close()

throw() injects an exception into a generator at the yield point. close() raises GeneratorExit to terminate it cleanly.

Example
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"
Pro Tip

Use finally in generators for cleanup — it runs on close() as well.