The Iterator Throw Method
You'll learn: How iterators can accept errors from the outside world using the optional throw() method.
What Is the Iterator Throw Method?
While the return() method lets you gracefully close an iterator, the throw() method allows you to inject an error into an iterator from the outside. Think of it like a fire alarm you can trigger remotely—instead of the building detecting smoke itself, someone outside can sound the alarm.
This method is optional, just like return(). If your iterator has a throw() method, external code can call it to signal that something went wrong, giving the iterator a chance to handle the error or clean up before failing.
How It Works
When you call iterator.throw(error), you're essentially throwing an exception inside the iteration logic. If the iterator is a generator (which you haven't learned yet), it can catch this error with try-catch blocks. If there's no throw() method defined, the error simply propagates normally.
const myIterator = {
value: 0,
next() {
return { value: this.value++, done: false };
},
throw(error) {
console.log('Error received:', error.message);
return { done: true }; // Stop iteration
}
};
myIterator.next(); // { value: 0, done: false }
myIterator.throw(new Error('Something broke!'));
// Logs: "Error received: Something broke!"
// Returns: { done: true }
When Would You Use This?
The throw() method is primarily useful when an external system needs to signal failure to an in-progress iteration—like a network request failing mid-stream or a user cancelling an operation.
Key Takeaway: The optional throw() method lets you send errors into an iterator from outside, giving it a chance to handle failures gracefully rather than just crashing.