(为什么)我不能从发电机中抛出异常吗?

时间:2015-03-28 16:22:24

标签: javascript generator ecmascript-6 throw babeljs

我试图从ES6生成器函数的主体中抛出异常,但它没有通过。这是ES6规范的一部分还是Babel的怪癖?

以下是我尝试的代码(on babeljs.io):

function *gen() {
    throw new Error('x');
}

try {
    gen();
    console.log('not throwing');
} catch(e) {
    console.log('throwing');
}

如果确实指定了ES6行为,那么发出异常信号的替代方法是什么?

1 个答案:

答案 0 :(得分:6)

您创建了一个迭代器,但没有运行它。

var g = gen();
g.next(); // throws 'x'

on babel repl

这是另一个例子:

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);
}