(为什么)我不能从生成器中抛出异常吗

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

本文关键字:抛出异常 为什么 不能      更新时间:2023-09-26

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

这是我尝试过的代码(在babeljs.io上):

function *gen() {
    throw new Error('x');
}
try {
    gen();
    console.log('not throwing');
} catch(e) {
    console.log('throwing');
}

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

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

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

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