Generator.prototype.throw()
Generator
实例的 throw()
方法的作用就好像在生成器主体的当前挂起位置插入了一条 throw
语句,该语句向生成器通知错误情况并允许其处理错误,或者执行清理并自行关闭。
¥The throw()
method of Generator
instances acts as if a throw
statement is inserted in the generator's body at the current suspended position, which informs the generator of an error condition and allows it to handle the error, or perform cleanup and close itself.
语法
参数
返回值
¥Return value
如果抛出的异常被 try...catch
捕获并且生成器恢复生成更多值,它将返回具有两个属性的 Object
:
¥If the thrown exception is caught by a try...catch
and the generator resumes to yield more values, it will return an Object
with two properties:
例外情况
描述
¥Description
调用 throw()
方法时,可以将其视为在生成器主体的当前挂起位置处插入了 throw exception;
语句,其中 exception
是传递给 throw()
方法的异常。因此,在典型的流程中,调用 throw(exception)
将导致生成器抛出异常。但是,如果 yield
表达式包含在 try...catch
块中,则可能会捕获错误,并且控制流可以在错误处理后恢复,或者正常退出。
¥The throw()
method, when called, can be seen as if a throw exception;
statement is inserted in the generator's body at the current suspended position, where exception
is the exception passed to the throw()
method. Therefore, in a typical flow, calling throw(exception)
will cause the generator to throw. However, if the yield
expression is wrapped in a try...catch
block, the error may be caught and control flow can either resume after error handling, or exit gracefully.
示例
使用 throw()
¥Using throw()
以下示例显示了一个简单的生成器以及使用 throw
方法引发的错误。像往常一样,错误可以被 try...catch
块捕获。
¥The following example shows a simple generator and an error that is thrown using the throw
method. An error can be caught by a try...catch
block as usual.
function* gen() {
while (true) {
try {
yield 42;
} catch (e) {
console.log("Error caught!");
}
}
}
const g = gen();
g.next();
// { value: 42, done: false }
g.throw(new Error("Something went wrong"));
// "Error caught!"
// { value: 42, done: false }
规范
Specification |
---|
ECMAScript Language Specification # sec-generator.prototype.throw |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also