How to catch exceptions in JavaScript?

To catch exceptions in JavaScript, use try...catch...finally. JavaScript implements the try...catch...finally construct as well as the throw operator to handle exceptions.

You can catch programmer-generated and runtime exceptions, but you cannot catch JavaScript syntax errors.

Syntax

try {
    // Code that may throw an exception
} catch (error) {
    // Handle the exception
} finally {
    // Optional - always executes
}

Example: Basic Exception Handling

Here's a simple example demonstrating exception catching:

<html>
   <head>
      <script>
         function myFunc() {
            var a = 100;
            try {
               alert("Value of variable a is : " + a);
            }
            catch (e) {
               alert("Error: " + e.message);
            }
            finally {
               alert("Finally block will always execute!");
            }
         }
      </script>
   </head>

   <body>
      <p>Click the following to see the result:</p>
      <form>
         <input type="button" value="Click Me" onclick="myFunc();" />
      </form>
   </body>
</html>

Example: Catching Runtime Errors

<html>
   <head>
      <script>
         function testError() {
            try {
               // This will cause a ReferenceError
               console.log(undefinedVariable);
            }
            catch (error) {
               alert("Caught error: " + error.message);
               console.log("Error type: " + error.name);
            }
            finally {
               console.log("Cleanup completed");
            }
         }
      </script>
   </head>

   <body>
      <button onclick="testError()">Test Error Handling</button>
   </body>
</html>

Throwing Custom Exceptions

You can also throw your own exceptions using the throw statement:

<html>
   <head>
      <script>
         function validateAge(age) {
            try {
               if (age < 18) {
                  throw new Error("Age must be 18 or older");
               }
               alert("Valid age: " + age);
            }
            catch (error) {
               alert("Validation failed: " + error.message);
            }
         }
      </script>
   </head>

   <body>
      <button onclick="validateAge(16)">Test Age 16</button>
      <button onclick="validateAge(25)">Test Age 25</button>
   </body>
</html>

Key Points

  • The try block contains code that might throw an exception
  • The catch block handles the exception if one occurs
  • The finally block always executes, regardless of whether an exception occurred
  • Use error.message to get the error description (not error.description)
  • JavaScript syntax errors cannot be caught at runtime

Conclusion

Exception handling in JavaScript uses try...catch...finally blocks to gracefully handle errors. The finally block ensures cleanup code runs regardless of success or failure.

Updated on: 2026-03-15T23:18:59+05:30

409 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements