Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Why) Can I not throw an exception out of a generator?

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?

like image 622
mhelvens Avatar asked Mar 28 '15 16:03

mhelvens


1 Answers

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);
}
like image 92
4 revs, 2 users 79%user1106925 Avatar answered Nov 18 '22 18:11

4 revs, 2 users 79%user1106925