[X]

Javascript Exception Handling Try-Catch-Throw - (Learning Javascript Series)

Javascript Exception/Error Handling

Exception handling is one of the difficult and oftenly avoided task by the developer. It is because handling exception requires almost equal amount of time and thinking from developer as given to the main program. In javascript 1.4 exception handling was supported by adding try-catch-throw to the language.

Exceptions are generally categorized in 2 types:

System Error: Caused by browser/code because of unknown reason(s).

Application Error: Caused by a piece of code where the scenario in which an error can occur is not handled by the developer.

Suppose we are writing a division program of two numbers and we have just coded assuming that everyting will be alright. But in the same program error can be thrown by some of the below reason:

  • User has not provided value to any of the 2 number (divisor or dividend)
  • User has entered 0 for divisor

So in above scenario an error can occur. If it is not handled by code, browser will show an annoying error message which user could not like at all and will be very embracing for developer.

Try-Catch

Try - Catch block was introduced in javascript 1.4, so only latest browser support it. We put the block of code inside try which we feel is prone to error.

Syntax:

 

try{

//block of error prone code

}

catch(variable){

//error handling code

//statements

}

Example:

 

<script type="text/javascript">
        var dividend = prompt("enter a dividend:");
        var divisor = prompt("enter a divisor:");
        //error prone code, not handled by try-catch
        //var quotient = parseInt(dividend) / parseInt(divisor);
        //alert(quotient);
        //handling error for above code

        try {
            var quotient = parseInt(dividend) / parseInt(divisor);
            if (quotient == "Infinity")
            { throw "Divison by zero occured."; }
            alert(quotient);
        }
        catch (Error) {
            alert("Following error occured: " + Error);
        }
       
    </script>

 

 

We saw how try-catch-throw can be used to handle expception. The efficiency of using exception handling is upto the programmer that how effectively it is being used. There may be scenarios where handling is must and also where it can be just not much feasible and waste of time.

blog comments powered by Disqus

Posts By Month