Hello! Welcome to the sixth lesson in our module on Iteration Protocols and Generator Functions.
In our previous lessons, we've seen how generators can produce sequences of values (yield), receive input from the caller (next(value)), and delegate to other iterables (yield*). We noted that yield* establishes a transparent communication channel, forwarding not just next() calls, but also throw() and return() calls.
Today, we'll explore that final piece of the generator's three-part API: the throw() method. This mechanism allows external code to inject errors directly into a generator's execution context, a powerful feature for building robust and interactive routines.
Our learning outcome is to: Implement error handling within a generator using the throw() method.
By the end of this lesson, you will be able to:
- Use the
iterator.throw()method to inject an error into a running generator. - Handle these injected errors inside the generator using
try...catchblocks. - Understand precisely where the error is thrown within the generator's execution context.
- Recognize how unhandled injected errors propagate out to the calling code.
- See how
throw()interacts withyield*delegation.
1. The throw() Method: Injecting Control Flow
At its core, a generator is a pausable function, or a coroutine. The next() method resumes it. The throw() method also resumes it, but with a twist: it does so by throwing an error at the exact point where the generator is paused.
Let's start with a resource that clearly illustrates the two primary scenarios: catching the error inside the generator, and letting it propagate out.
The javascript.info guide provides a concise and excellent explanation of the generator.throw() mechanism. It's the perfect starting point.
Read the section titled 'generator.throw'. Pay close attention to the two code examples. The first shows how try..catch can be used to handle an injected error internally. The second shows what happens when the error is not caught inside the generator.
2. Handling Injected Errors with try...catch
As you've just read, the standard JavaScript try...catch statement is the tool for handling errors injected via throw(). By wrapping a yield expression in a try block, you give the generator the ability to gracefully manage external error signals instead of crashing.
Let's look at a practical example. Imagine a generator that performs a multi-step process. The calling code might need to abort this process if an external event occurs.
function* processingTask() {
console.log("Starting task...");
try {
yield "Step 1 complete. Waiting for confirmation to proceed.";
yield "Step 2 complete. Finalizing...";
// This part is never reached if an error is thrown on the previous yield
} catch (e) {
console.error(`[Generator] Caught an error: ${e.message}. Rolling back.`);
// A generator can yield a final status after catching an error
yield "Task aborted due to error.";
}
return "Task finished.";
}
const iterator = processingTask();
// Start the task
console.log(iterator.next().value); // Logs "Starting task..." then "Step 1 complete..."
// Instead of proceeding with next(), we inject a cancellation error.
const result = iterator.throw(new Error("External cancellation signal received"));
// The catch block in the generator runs.
console.log(result.value); // "Task aborted due to error."
console.log(result.done); // false
// The generator continues after the catch block.
console.log(iterator.next()); // { value: 'Task finished.', done: true }
This demonstrates a key concept: throw() isn't just for crashing the generator. It's a form of communication. The generator can catch the "error" signal, perform cleanup or alternate logic (like a rollback), and even decide to continue or terminate gracefully.
3. The Execution Context: Where is the Error Thrown?
This is a critical detail that your computer science background will help you appreciate. The error is not thrown from the generator function in general, but specifically at the yield expression that caused the last suspension. The state of the generator's call stack and variable scope is preserved, and the throw effectively replaces the return value of the yield expression with an exception.
The following resource provides a superb, detailed analysis of this behavior.
Generators in JavaScript, Part III - "Advanced" Concepts
To really solidify your understanding of where the error is injected, let's look at a more detailed analysis. This article from dev.to provides an excellent breakdown.
Read the section titled 'throw() with generators'. Focus on its explanation of how throw() injects an error that can be handled by try/catch. Pay special attention to the getNumbers example at the end, which masterfully illustrates how the error is thrown at the currently suspended yield statement, and how that affects which catch block (if any) can handle it.
As the article demonstrated, the location of the try...catch block in relation to the paused yield statement is what determines if an error is caught.
Let's recap the getNumbers example from the article, as it's a perfect illustration:
function* getNumbers() {
yield 1;
try {
yield 2;
} catch {
console.log('Caught error at yield 2!');
}
yield 3;
}
iterator.next(): Execution runs toyield 1and pauses.iterator.throw(): An error is thrown at theyield 1line. Since this is outside thetry...catchblock, the error is uncaught within the generator and propagates to the caller.iterator.next()(again): Execution resumes fromyield 1, enters thetryblock, runs toyield 2, and pauses.iterator.throw()(now): An error is thrown at theyield 2line. Since this is inside thetry...catchblock, thecatchblock executes, and the generator continues.
4. Uncaught Errors and yield*
If an error injected with throw() is not caught inside the generator, it propagates out to the caller. The exception will then occur in the caller's scope at the line where iterator.throw() was called.
This behavior is consistent with standard JavaScript error propagation and is precisely what you saw in the second example from the javascript.info article.
This also ties directly into our last lesson on yield*. Since yield* creates a transparent proxy to the delegated iterator, a throw() call on the outer iterator is forwarded to the inner one.
- If the inner generator catches the error, it handles it, and execution continues as defined by the inner generator's logic.
- If the inner generator does not catch the error, the error propagates back out to the
yield*expression in the outer generator, where it can then be caught.
Consider this composition:
function* innerTask() {
try {
yield 'Inner task working...';
} finally {
// This cleanup code will run whether the generator finishes
// normally, is returned from, or has an error thrown.
console.log('[Inner] Cleaning up resources.');
}
}
function* outerTask() {
try {
yield 'Outer task started.';
yield* innerTask();
yield 'Outer task resuming.'; // Will not be reached
} catch (e) {
console.log(`[Outer] Caught error from sub-task: ${e.message}`);
}
return 'All tasks complete.';
}
const it = outerTask();
it.next(); // { value: 'Outer task started.', done: false }
it.next(); // { value: 'Inner task working...', done: false } (from innerTask)
// Now, throw an error into the composed generator
it.throw(new Error('System failure!'));
// Console output:
// [Inner] Cleaning up resources.
// [Outer] Caught error from sub-task: System failure!
// The outer generator caught the error and can now continue.
console.log(it.next()); // { value: 'All tasks complete.', done: true }
This powerful pattern allows you to compose complex, stateful operations from smaller generator units while maintaining robust, centralized error handling.
Test your understanding!
Imagine a generator that attempts to connect to a database. It will yield a "connecting..." status. The calling code should simulate a connection timeout by using setTimeout to call iterator.throw() after 1 second if the connection hasn't been "established" by then.
- Create a generator
dbConnection()that yields 'Connecting...'. - Inside the generator, wrap the
yieldin atry...catchblock. - The
catchblock should log an error message like "Connection timed out!" and the generator should then terminate.
How would you orchestrate this from the calling code?
Show answer
function* dbConnection() {
try {
console.log("Attempting to establish connection...");
// The generator will pause here, waiting for the next call.
yield "Connecting...";
// This part is only reached if next() is called, not throw().
console.log("Connection established successfully!");
} catch (e) {
console.error(`[Generator] DB Error: ${e.message}`);
} finally {
console.log("[Generator] Closing connection resources.");
}
}
const iterator = dbConnection();
console.log(iterator.next().value); // Logs "Attempting..." and then "Connecting..."
// Simulate a timeout
setTimeout(() => {
// If we get here, the connection wasn't "established" in time.
iterator.throw(new Error("Connection timed out after 1s"));
}, 1000);
When you run this code, you'll see the initial log, then after one second, the setTimeout callback will fire, injecting the error. The generator's catch block will execute, followed by its finally block, demonstrating a complete error handling and cleanup flow initiated from outside the generator.
Conclusion
You have now mastered the full three-part API of the generator-iterator: next(), return(), and throw(). This allows for sophisticated, two-way, stateful communication between a generator and its controlling code.
Key Takeaways:
iterator.throw(error)resumes a generator's execution by injecting an error at the currently pausedyieldstatement.- This mechanism allows calling code to signal error or cancellation conditions to the generator.
- Injected errors can be handled inside the generator using standard
try...catchblocks, allowing for cleanup, recovery, or graceful termination. - If an injected error is not caught internally, it propagates out to the caller, throwing an exception at the site of the
iterator.throw()call. yield*seamlessly forwardsthrow()calls, enabling robust error handling across composed generators.
Next Up
Having covered the complete interface for controlling generators, we'll now turn our attention back to a primary use case that their pausable, lazy nature enables. In the next lesson, we will use generators to build and consume infinite data sequences, a pattern that is inefficient or impossible with regular functions and arrays.