Javascript - Generator with try-catch block


throw(...) stops the execution of the generator but it is never called automatically.

Using a try-catch block to enable error handling in generators.

function *getFruits() { 
          yield "XML"; 
          yield "Keyboard"; 
          yield "spinach"; 
          yield "watermelon" 

const fruitIterator = getFruits(); 

for (let fruit of fruitIterator) { 
        try { 
            if (fruit === "spinach") { 
                  fruitIterator.throw("Vegetable Found"); 
        catch (err) { 
            console.log(`Exception: ${err}`); 

// XML 
// Keyboard 
// spinach 
// Exception: Vegetable Found 

"watermelon" never got yielded from the generator because throw() was called when "spinach" was returned, halting the execution of the sequence.

Related Topic