Course contentsShow
← Python
Lesson 311 of 1,0605. Advanced Iteration and ComprehensionsFree lesson

Handling Generator Exceptions with Throw and Close

You will learn to manage state and cleanup operations by injecting exceptions into generators using the throw and close methods.

In this lesson, you will learn how to proactively manage a generator’s state and trigger cleanup operations by injecting exceptions into its execution flow using throw and close.

Sometimes, a generator might be stuck in a waiting state or performing a long-running process that needs to be interrupted. Instead of simply abandoning the generator, Python allows you to "force" an event inside the generator's current execution point.

Using throw()

The throw() method allows you to inject an exception into a generator at the point where it is currently suspended. Once you call throw(), the generator behaves as if it raised that exception itself. This is useful if you want to notify a generator that something went wrong in your main program, allowing the generator to handle the error locally.

def task_manager():
    try:
        while True:
            yield "Working..."
    except ValueError:
        print("Caught a value error inside the generator!")

gen = task_manager()
next(gen)
gen.throw(ValueError) # Injects the exception into the generator

Using close()

While throw() lets you handle an error, close() is used to permanently shut down a generator. When you call close(), it raises a GeneratorExit exception inside the generator. This is a special signal that tells the generator to stop what it is doing and perform any necessary cleanup—like closing a file handle or releasing a database connection—within a finally block.

def persistent_writer():
    try:
        while True:
            yield "Writing data..."
    finally:
        print("Cleaning up resources before closing.")

gen = persistent_writer()
print(next(gen))
gen.close() # Triggers the finally block and stops the generator

By using these two methods, you stop treating generators as simple "data factories" and start treating them as robust, manageable components that can respond gracefully to unexpected changes in your program’s lifecycle.

Key Takeaway: Use throw() to send custom signals or errors into a generator for local handling, and use close() to gracefully terminate a generator and trigger essential cleanup logic.