JavaScript Error and Exceptional Handling with Example

JavascriptWeb DevelopmentObject Oriented Programming

Let us see an example to implement error and exception handling concepts with JavaScript −

Example

 Live Demo

<!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;
   }
   .sample {
      font-size: 18px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>Error and exceptional handling example</h1>
<div class="sample"></div>
<input class="inputNum" type="number" />
<input class="inputNum" type="number" />
<button class="Check">DIVIDE</button>
<h3>
Click on the above buttons to do division
</h3>
<script>
   let sampleEle = document.querySelector(".sample");
   let num, num1;
   document.querySelector(".Check").addEventListener("click", () => {
      num = document.querySelectorAll(".inputNum")[0].value;
      num1 = document.querySelectorAll(".inputNum")[1].value;
      try {
         if (num1 === "0") throw "Can't divide by zero";
         sampleEle.innerHTML = `${num} divide by ${num1} = ${num / num1}`;
      } catch (e) {
         sampleEle.innerHTML = "Error: " + e;
      }
   });
</script>
</body>
</html>

Output

On entering the second number as 0 and clicking DIVIDE −

raja
Published on 07-May-2020 14:39:32
Advertisements