Chitika

Sunday, October 14, 2012

Exception Handling Techniques in JavaScript

Exception handling in java script is almost same like how we do exception handling in c#.
In this article i am going to show you, how to do exception handling using java script.
Various techniques of JavaScript exception handling are dicussed here
Like the Object oriented programming the exception handling is not implemented while coding in JavaScript. i.e in most of cases if there is any problem in one part in a page then surprisingly other part also stops working. 

In this post we will be discussing the various techniques to handle exceptions in JavaScript.

Using try..catch block
try..catch block in JavaScript is very much similar to the regular C# try..catch block. 
The suspected code will be put in try block and all exceptions which will occur in the try block will be caught in catch block.

window.onload = function()
{
    try
    {
        var x = 90;
        var value = x / y;
    }
    catch(err)
    {
        document.write(err.name + ": " + err.message + "<br/>");
    }
}
Output:
TypeError: 'y' is undefined

In catch you will get the object containing type and description of the exception. More over you can also use finally block in the same way as you use in C#.

window.onload = function()
{
    try
    {
        var x = 90;
        var value = x / y;
    }
    catch(err)
    {
        document.write(err.name + ": " + err.message + "<br/>");
    }
    finally
    {
        alert('This is finally block');
    }
}

Using onerror event

onerror event will be raised each time there is any error while performing a action in the document. This like on place exception handling similar to Application_Error in ASP.NET. Here is sample code which demonstrate this:

window.onload = function()
{
    var x = 90;
    var value = x / y;
}

window.onerror = function(errorMeaage, fileName, lineNumber)
{
    document.write('Error: ' + errorMeaage);
}

Using jQuery Solution

It is similar to using onerror but with jQuery syntax. 
The syntax is:

$(window).error(
    function(errorMeaage, fileName, lineNumber)
    {
        // handle error here
    }
);






No comments:

Post a Comment