Error Handling with throw()
You'll learn how to inject exceptions into a running generator from the outside, giving you fine-grained control over error handling at specific yield points.
What is throw() on Generators?
Just like you can pass values into a generator with next(value), you can also throw errors into it using the throw() method. When you call generatorObject.throw(error), the generator behaves as if the current yield expression threw that error internally.
This means the generator can use try-catch blocks to handle errors exactly where execution is paused, making error handling feel natural and synchronous even though the execution is suspended and resumed.
How It Works
Think of a generator as a conversation. With next(), you're saying "continue, here's some data." With throw(), you're saying "something went wrong, deal with this error right where you paused."
function* cautious() {
try {
const value = yield 'Waiting for input...';
yield `Received: ${value}`;
} catch (error) {
yield `Error caught: ${error.message}`;
}
yield 'Generator recovered!';
}
const gen = cautious();
console.log(gen.next()); // { value: 'Waiting for input...', done: false }
console.log(gen.throw(new Error('Oops!'))); // { value: 'Error caught: Oops!', done: false }
console.log(gen.next()); // { value: 'Generator recovered!', done: false }
The error is thrown at the yield point where the generator is paused. If there's no try-catch inside the generator, the error propagates out to the caller.
When to Use throw()
Use throw() when you need to signal exceptional conditions from the outside world back into the generator's execution flow—perfect for async operations where something external fails.
Key Takeaway: The throw() method lets you inject exceptions into a suspended generator, enabling error handling at the exact yield point where execution is paused.