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.
In this article
Syntax
generatorInstance.throw(exception)Parameters
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:
Exceptions
TypeErrorThrown 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.
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> |