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 −


 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;
   .sample {
      font-size: 18px;
      font-weight: 500;
<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>
Click on the above buttons to do division
   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;


On entering the second number as 0 and clicking DIVIDE −

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