JavaScript | Generator.prototype.throw() Method

The Generator.prototype.throw() method is an inbuilt method in JavaScript which is used to resumes the execution of a generator by throwing an error into it.

Syntax:

gen.throw(exception);

Parameters: This function accepts single parameter as mentioned above and described below:

  • exception: This parameter holds the exception to be thrown.

Return value: This method returns an Object containing two properties:

  1. done: It has the value
    • true – for the iterator which past the end of the iterated sequence.
    • false – for the iterator which are able to produce the next value in the sequence.
  2. value: It contains any JavaScript value which is returned by the iterator.

Below examples illustrate the Generator.prototype.throw() method are listed below:



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
function* GFG() {
  while(true) {
    try {
       yield "Null";
    } catch(e) {
      console.log('Generator.prototype.throw()');
    }
  }
}
  
const geeks = GFG();
console.log(geeks.next());
console.log(geeks.throw(new Error('Error caught!')));       
</script>   

chevron_right


Output:

Object { value: "Null", done: false }
"Generator.prototype.throw()"
Object { value: "Null", done: false }

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
function* GFG(pageSize = 1, list) {
    let output = [];
    let index = 0;
  
    while (index < list.length) {
      try {
        output = [];
        for (let i = index; i < index + pageSize; i++) {
            if (list[i]) {
                output.push(list[i]);
            }
        }
  
        yield output;
        index += pageSize;
      } catch(e) {
      console.log('Generator.prototype.throw()');
    }
    }
}
list = [1, 2, 3, 4, 5, 6, 7, 8]
var geek = GFG(3, list);              
  
console.log(geek.next());      
console.log(geek.next());      
console.log(geek.next()); 
console.log(geek.throw(new Error('Error caught!')));
</script> 

chevron_right


Output:

Object { value: Array [1, 2, 3], done: false }
Object { value: Array [4, 5, 6], done: false }
Object { value: Array [7, 8], done: false }
"Generator.prototype.throw()"
Object { value: Array [7, 8], done: false }

Supported Browsers: The browsers supported by Generator.prototype.throw() method are listed below:

  • Google Chrome
  • Firefox
  • Opera
  • Safari
  • Edge

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.