I'm trying to throw an exception from the body of an ES6 generator function, but it's not going through. Is this part of the ES6 specification or a quirk of Babel?
Here is the code I tried (on babeljs.io):
function *gen() {
throw new Error('x');
}
try {
gen();
console.log('not throwing');
} catch(e) {
console.log('throwing');
}
If this is indeed specified ES6 behavior, what's an alternative approach for signalling an exception?
You created an iterator but didn't run it.
var g = gen();
g.next(); // throws 'x'
(on babel repl)
Here's another example:
function *gen() {
for (let i=0; i<10; i++) {
yield i;
if (i >= 5)
throw new Error('x');
}
}
try {
for (n of gen())
console.log(n); // will throw after `5`
console.log('not throwing');
} catch(e) {
console.log('throwing', e);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With