throw
()
方法用来向生成器抛出异常,并恢复生成器的执行,返回带有 done
及 value
两个属性的对象。
gen.throw(exception)
exception
Error
的实例对调试非常有帮助.带有两个属性的对象
:
done
(boolean)
true
。在这种情况下,可以
指定迭代器 value
的返回值。 false
。 这相当与不指定 done 属性的值。value
- 迭代器返回的任何 JavaScript 值。当 done 是 true 的时候可以省略。throw()
下面的例子展示了一个简单的生成器并使用 throw方法向该生成器抛出一个异常,该异常通常可以通过 try...catch
块进行捕获.
function* gen() {
while(true) {
try {
yield 42;
} catch(e) {
console.log("Error caught!");
}
}
}
var g = gen();
g.next(); // { value: 42, done: false }
g.throw(new Error("Something went wrong")); // "Error caught!"
Specification | Status | Comment |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262) Generator.prototype.throw |
Standard | Initial definition. |
ECMAScript Latest Draft (ECMA-262) Generator.prototype.throw |
Draft |
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | ? | 26 (26) | ? | ? | ? |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | ? | ? | 26.0 (26) | ? | ? | ? |