The throw(exception) method

You can manually trigger an exception inside a generator function using the throw() method of the generator object. You must pass an exception to the throw() method that you want to throw. Here is an example to demonstrate this:

function* generator_function(){ try {  yield 1; } catch(e) {  console.log("1st Exception"); } try {  yield 2; } catch(e) {  console.log("2nd Exception"); }}const generator = generator_function();console.log(generator.next().value);console.log(generator.throw("exception string").value);console.log(generator.throw("exception string").done);

The output is as follows:

11st Exception22nd Exceptiontrue

In the preceding example, you can see that the exception is thrown where the function was last paused. ...

Get Learn ECMAScript - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.