Computer >> Computer tutorials >  >> Programming >> Javascript

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 −

Example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result,.sample {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
   .result {
      color: red;
   }
</style>
</head>
<body>
<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>
<script>
   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 = inc.next().value + " ";
   });
   BtnEle[1].addEventListener("click", () => {
      inc.throw(new Error("Some error occured"));
   });
</script>
</body>
</html>

Output

The above code will produce the following output −

The generator.throw() method in JavaScript.

On clicking ‘Display Num’ button a few times −

The generator.throw() method in JavaScript.

On clicking ‘Throw Error’ button −

The generator.throw() method in JavaScript.