Javascript Generator with try...catch inside and outside

Introduction

Generators can have a throw function, either inside the generator or outside of it.

function *insideThrow(){ 
     while(true){ 
        try{ /*from  w w  w.  ja  v a2  s .  com*/
            yield 'inside try block'; 
        }catch(e){ 
            console.log('inside catch') 
        } 
     } 
} 
let it = insideThrow(); 
console.log(it.next());  // Object {value: "inside try block", done: false}
console.log(it.throw(new Error('this is an error'))) // catch runs and
                            // returns last yield
value Object {value: "inside try block", done: false} 


function *outsideThrow(){ 
     let value =  yield value; 
     return value; 
} 

let it2 = outsideThrow(); 
console.log(it2.next());  // Object {value: undefined, done: false}

try{ 
   console.log(it2.next('outside try block'));  // Object {value: "outside try
                        // block",done: true}
   console.log(it2.throw(new Error('this is an error')));  // catch runs
}catch(e){ 
   console.log('outside catch') 
} 



PreviousNext

Related