Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. JavaScript
  3. Reference
  4. Standard built-in objects
  5. Generator
  6. throw()

Generator.prototype.throw()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨September 2016⁩.

Thethrow() method ofGenerator instances acts as if athrow 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

The exception to throw. For debugging purposes, it is useful to make it aninstanceofError.

Return value

If the thrown exception is caught by atry...catch and the generator resumes to yield more values, it will return anObject with two properties:

done

A boolean value:

  • true if the generator function's control flow has reached the end.
  • false if the generator function is able to produce more values.
value

The value yielded from the nextyield expression.

Exceptions

TypeError

Thrown if the generator is already running.

If theexception is not caught by atry...catch within the generator function, it is also thrown to the caller ofthrow().

Description

Thethrow() method, when called, can be seen as if athrow exception; statement is inserted in the generator's body at the current suspended position, whereexception is the exception passed to thethrow() method. Therefore, in a typical flow, callingthrow(exception) will cause the generator to throw. However, if theyield expression is wrapped in atry...catch block, the error may be caught and control flow can either resume after error handling, or exit gracefully.

Examples

Using throw()

The following example shows a generator and an error that is thrown using thethrow method. An error can be caught by atry...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 }

Specifications

Specification
ECMAScript® 2026 Language Specification
# sec-generator.prototype.throw

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp