JavaScript Error Handling

Exception handling or Error Handling is the method of responding to the occurrence of errors during the program execution. In JavaScript the try catch finally statement are used to handle the exceptions gracefully. The block structure of try catch finally statement is as follows :
 try {
   // Statements
 } catch ( e ) {
   // Statements
 } finally {
   // Statements
 }
Where
  • The try statement allows to define a block of code to be tested for errors while it is being executed
  • The catch statement allows to define a block of code to be executed, if an error occurs in the try block.
  • The final statement let us execute code, after try and catch, regardless of the result.

The JavaScript try block will execute the code and in-case if error occurred in execution flow then the JavaScript will normally stop execution and throw exception which is handled by the catch block. Now lets see an example :
<script>
  try {
    Myfunc();
  } catch(err) {
    document.write(err.message);
  }
</script>
Output :


At the above code the function Myfunc() is not defined, show the try block will throw an exception which is handled by the catch block by the argument err. And we are able to see the error message by using err.message statement, where the err (or error) is a built-in JavaScript object. And also the above code block: catch and finally statements are optional. The final code block will always execute after the try catch block, weather if exception is thrown or not.

Example 1 :
<script>
  try {
    Myfunc();
  } catch(err) {
    document.write(err.message);
  } finally {
    document.write("<br/>This is the rest of code to execute.");
  }
</script>
Output :


Example 2 :
<script>
  try {
    document.write("hello world");
  } catch(err) {
    document.write(err.message);
  } finally {
    document.write("<br/>This is the rest of code to execute.");
  }
</script>
Output :



throw statement :

The throw statement allows the users to create and throw user defined exception, where the exception can be a JavaScript string, a number, a boolean or an object. With throw statement we can control the program flow and generate the custom error messages. Lets see an Example :
<html>
<body>
  <p>Enter 10 digit Phone Number</p>
  <input type="text" id="phn">
  <p id="demo"></p>
  <input type="button" onclick="MyFunc()" value="validate Number"/> 
  <script>
    function MyFunc() {
      var number = document.getElementById("phn").value;
      var text = document.getElementById("demo");
      try {
        if(number.length < 10) throw "Less than 10 digits";
        if(number.length > 10) throw "Greater than 10 digits";
        if(isNaN(number) == true) throw "Not a Number"; 
        text.innerHTML = "Your Number <b>" + number + "</b> is Validated.";
      } catch(err) {
        text.innerHTML = "Error : Input is " + err;
      }
    }
</script>
</body>
</html>
Output :

Enter 10 digit Phone Number


Now at the above example the the the try/catch statement is used inside the function, where the user given number is tested with the if condition and the errors are thrown if the condition is true and the catch block will print the error message on the page.


Next Topic :