(为什么)我不能从生成器中抛出异常吗
(Why) Can I not throw an exception out of a generator?
我试图从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);
}
相关文章:
- 为什么浏览器没有为语法错误抛出异常
- PHP REST服务抛出异常——希望避免控制台错误
- 测试抛出异常的函数
- (为什么)我不能从生成器中抛出异常吗
- 如何抛出异常
- 抛出异常:Node.js与Gevent
- 当请求DOM对象时,XMLHttpRequest.send()抛出异常
- AngularJS在尝试轻松保存Changes时抛出异常
- $mdDialog.prompt 抛出异常,但该函数在确认时工作正常
- 在 Javascript 中,即使从未抛出异常,使用 try-catch 块是否昂贵
- 自定义抛出异常JavaScript的错误消息
- 在网格弹出编辑器中上传剑道:如何防止上传抛出异常时窗口关闭
- 为什么抛出异常后不再被视为已发生
- 为什么“;[value='']”;在IE7中抛出异常并且“:not(:not([value='&
- Div内的脚本标签抛出异常-为什么
- 为什么节点mkdirSync()抛出异常
- IE9在iframe中加载脚本时抛出异常.为什么?
- 为什么for..in会优雅地失败,而for..of会抛出异常?
- 为什么给定代码会抛出异常(Jsoup)
- JavaScript -为什么推送不工作并抛出异常