The generator.throw() method in JavaScript.

The generator.throw() method is used to pass an error to the yield. The generator resumes the execution after throw has been called by throwing an error and returning object with properties done and value.

Following is the code for generator.throw() in JavaScript −


 Live Demo

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   .result,.sample {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   .result {
      color: red;
<h1>generator.throw() method in Javascript</h1>
<div class="sample"></div<
<div class="result"></div>
<button class="Btn">Display Num</button>
<button class="Btn">Throw Error</button>
<h3>Click on the above buttons to display num or throw error</h3>
   let BtnEle = document.querySelectorAll(".Btn");
   let resEle = document.querySelector(".result");
   let sampleEle = document.querySelector(".sample");
   function* increment() {
      let num = 0;
      while (true) {
         try {
            yield num++;
         catch (err) {
            resEle.innerHTML = "Error = " + err + "<br>";
   let inc = increment();
   BtnEle[0].addEventListener("click", () => {
      sampleEle.innerHTML = + " ";
   BtnEle[1].addEventListener("click", () => {
      inc.throw(new Error("Some error occured"));


The above code will produce the following output −

On clicking ‘Display Num’ button a few times −

On clicking ‘Throw Error’ button −

Updated on: 17-Jul-2020


Kickstart Your Career

Get certified by completing the course

Get Started