The following code shows an Example of Exception Handling in JavaScript. An exception is an error that occurs at runtime. In the try block, we specify the statements that may cause error. Further, the catch block executes in case an error occurs. While, the finally block always executes irrespective of whether the error has occurred or not.

In the following example, an exception occurs since the function A_Sample_Method() is not defined.

<html>
 <head>
   <title>Exception Handling in Javascript</title>
    <script>
    try{
          A_Sample_Method("hello");
    }
    catch(err){
      document.write("Undefined method... "+err.message);
    }
    finally{
       document.write("<br/>Welcome to programmingempire.com");
    }
   </script>
   <style>
     body{
        color: #992288;
        background: #ffddff;
	font-size: 20px;
     }
   </style>
 </head>
 <body>

 </body>
</html>

Output

Exception Handling Using try, catch, and finally in JavaScript
Exception Handling Using try, catch, and finally in JavaScript