我为什么不能在生成器中抛出异常?

8

我正在尝试从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个回答

12
你创建了一个迭代器但没有运行它。
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);
}

谢谢!回想起来,那很有道理。如果我想在调用.next()之前抛出异常,我必须创建一个普通函数来封装生成器函数。 - mhelvens
有用的是抛出一个 StopIteration - user5321531

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接