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.
Python code
32 linesdef 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
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
- Use `gen.close()` to raise `GeneratorExit` inside the generator and require cleanup.
- 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
More from Comprehensions & generators
- Batch Rows in Chunks with a Generator in Python easy
- Build a Generator Pipeline in Python: Filter Then Map medium
- Build a lazy generator to read file lines in Python easy
- Chunk an Iterable into Batches with a Generator in Python easy
- Convert Data in Python with Comprehensions and Generators easy
- Count Data in Python with Comprehensions and Generators easy
Keep learning
Related tutorials and quizzes for this topic.