How to Throw an Exception into a Python Generator

This code demonstrates how to use the .throw() method on a generator to inject an exception at its current yield point and let it recover gracefully.

Medium Python 3.9+ Aug 9, 2026 Comprehensions & generators 12 views 0 copies

Python code

32 lines
Python 3.9+
def demo_throw_into_generator():
    """Demonstrate throwing an exception into a running generator."""
    def counter():
        """Generator that counts until interrupted."""
        try:
            i = 0
            while True:
                yield i
                i += 1
        except ValueError as e:
            print(f"Caught in generator: {e}")
            yield f"Generator recovered from: {e}"

    gen = counter()
    
    # Get first two values
    print(next(gen))  # 0
    print(next(gen))  # 1
    
    # Throw an exception into the generator
    result = gen.throw(ValueError("Something went wrong!"))
    print(result)
    
    # Generator is exhausted after handling
    try:
        next(gen)
    except StopIteration:
        print("Generator exhausted")


if __name__ == "__main__":
    demo_throw_into_generator()

Output

stdout
0
1
Caught in generator: Something went wrong!
Generator recovered from: Something went wrong!
Generator exhausted

How it works

The gen.throw(ValueError("Something went wrong!")) call resumes the generator at the point where it last yielded, raising the given exception inside the generator's yield expression. The generator's try/except catches the injected ValueError, prints a message, and yields a recovery value that gets returned to the caller. After the except block completes, the generator has no more yield statements to execute, so the next next(gen) raises StopIteration. This demonstrates how generators can handle external interruptions or errors without losing their internal state.

Common mistakes

  • Forgetting that `throw()` only works on an already-started generator (you must call `next()` at least once).
  • Misplacing the `except` block inside the generator so it never catches the injected exception.

Variations

  1. Use `gen.close()` to raise `GeneratorExit` inside the generator and require cleanup.
  2. Catch `StopIteration` explicitly to handle generator exhaustion instead of letting it propagate.

Real-world use cases

  • Cooperative cancellation: inject a `CancelledError` into a long-running generator to interrupt it cleanly.
  • Error propagation from a pipeline: send an exception into a generator stage when upstream data fails validation.
  • Timeout handling in streaming: throw a `TimeoutError` into a generator that is blocked on slow input to trigger recovery logic.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Comprehensions & generators

Related tutorials and quizzes for this topic.