Explain try and catch statements in JavaScript with examples.

JavascriptWeb DevelopmentObject Oriented Programming

The try statement allows us execute a block of code and test for errors. Those errors are then caught and handle by the catch statement.

Following is the code for try and catch statement in 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;
   }
   .result {
      font-size: 20px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>Try and catch in JavaScript</h1>
<div style="color: green;" class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to call a variable before it is defined
</h3>
<script>
   let resEle = document.querySelector(".result");
   document.querySelector(".Btn").addEventListener("click", () => {
      try {
         resEle.innerHTML = a;
      }
      catch (err) {
         resEle.innerHTML = "Error = " + err;
      }
      let a = 44;
   });
</script>
</body>
</html>

Output

The above code will produce the following output −

On clicking the ‘CLICK HERE’ button −

raja
Published on 15-Jul-2020 17:40:23
Advertisements