Course contentsShow
← JavaScript
Lesson 1091 of 2,72325. Iterators and GeneratorsFree lesson

Error Handling with throw()

Explore the optional throw() method for propagating errors into an iterator.

Error Handling with throw()

You'll learn how iterators can receive and handle errors from the outside using the optional throw() method.

The Core Idea

Iterators aren't just one-way streets where you call next() and get values. They can also receive errors from the consumer. The optional throw() method lets you inject an exception into the iterator, allowing it to react — perhaps by cleaning up resources, logging the error, or yielding a fallback value before terminating.

Think of it like this: if next() is asking "what's next?", throw() is saying "something went wrong out here — deal with it!"

How It Works

When you call iterator.throw(error), the iterator receives that error at the point where it last paused. If the iterator has a try...catch block internally, it can catch and handle the error. If not, the error propagates out to the caller.

function* resilientGenerator() {
  try {
    yield 1;
    yield 2; // This line runs when throw() is called
  } catch (err) {
    console.log("Caught:", err.message);
    yield "recovered";
  }
}

const iter = resilientGenerator();
console.log(iter.next()); // { value: 1, done: false }
console.log(iter.throw(new Error("Oops!"))); 
// Logs: "Caught: Oops!"
// Returns: { value: "recovered", done: false }
console.log(iter.next()); // { value: undefined, done: true }

Without a try...catch, the error would crash the iterator and terminate it immediately.

When to Use It

The throw() method is rare in everyday code but valuable when building robust iterator pipelines that need to handle external failures gracefully — like stopping a data stream cleanly when a network error occurs.

Key Takeaway: The throw() method propagates errors into an iterator, letting it catch and respond to exceptions from the consumer side, enabling more resilient iteration patterns.