In this article we will discuss how to handle exception in JavaScript. The exception may occur at run time due to errors such as referencing a variable or a method that is not defined. Below example program has method name addNumbers() but here I have mistakenly call as addNumber() I have missed letter ‘s’ .when a specific line in the try block causes as exception. It was handled immediately to the catch block skipping the rest of code in the try block.

Example:

<script type="text/javascript">

    try {

        // Referencing a function thatdoes not exist cause an exception

       document.write(addNumber());

        // Since the above line causes anexception, the following line will not be executed

       document.write("twonumber added sucess.");

    }

    // When an exception occurs, ittransferred to the catch block

    catch (e) {

       document.write("Description= " + e.description+ "<br/>");

       document.write("Message= " + e.message + "<br/>");

       document.write("Stack= " + e.stack + "<br/><br/>");

    }

    function addNumbers() {

        var firstNumber = parseFloat(document.getElementById("txtFirstNumber").value);

        if (isNaN(firstNumber)) {

           alert("Pleaseenter a valid number in the first number textbox");

            return;

        }

        var secondNumber = parseFloat(document.getElementById("txtSecondNumber").value);

        if (isNaN(secondNumber)) {

           alert("Pleaseenter a valid number in the second number textbox");

            return;

        }

       document.getElementById("txtResult").value = firstNumber + secondNumber;

    }

  </script>

 

Output: