How to catch exceptions in JavaScript?

JavascriptWeb DevelopmentFront End Technology

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.


You can try to run the following code to learn how to catch exceptions in JavaScript −

 Live Demo

            function myFunc() {
               var a = 100;
               try {
                  alert("Value of variable a is : " + a );
               catch ( e ) {
                  alert("Error: " + e.description );
               finally {
                  alert("Finally block will always execute!" );

      <p>Click the following to see the result:</p>

         <input type = "button" value = "Click Me" onclick = "myFunc();" />
Updated on 16-Jan-2020 09:15:08