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.

语法

¥Syntax

js
generatorInstance.throw(exception)

参数

¥Parameters

exception

要抛出的异常。出于调试目的,将其设置为 instanceof Error 很有用。

返回值

¥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:

done

布尔值:

  • 如果生成器函数的控制流已到达末尾,则为 true
  • false 如果生成器函数能够产生更多值。
value

从下一个 yield 表达式产生的值。

例外情况

¥Exceptions

如果抛出的异常没有被 try...catch 捕获,则传递给 throw()exception 将从生成器函数中抛出。

¥If the thrown exception is not caught by a try...catch, the exception passed to throw() will be thrown out from the generator function.

描述

¥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.

示例

¥Examples

使用 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.

js
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

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看

¥See also