JavaScript Exception Handling Techniques

Like the Object oriented programming the exception handling is also not used while coding in JavaScript. That why 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
    }
);

15 comment(S)


very cool &amp; good tip, thank you very on Aug 5, 2009 12:54 AM

very cool & good tip, thank you very much for sharing.

Can I share this snippet on my <a href="http://javascriptbank.com/">JavaScript library</a>?


Awaiting your response. Thank

Aaron White on Aug 10, 2009 01:39 PM

Nice post on error catching. I'm building a service that lets people instrument their website to catch Javascript errors (development & production), logging them to a hosted server (Issue management UI, etc). I'm trying to collect early alpha feedback.. it's 1 line of JS code, would be great if you wanted to give it a whirl; Rerrorize.com

Jakub W&#243;jciak on Aug 14, 2009 02:08 AM

The window.onerror does not catch all exceptions. Firefox 2 didn't invoke it when an exception occured in an event handler. I don't know whether it's fixed by now.

I wrap the event attaching code in my own pass-through handler that catches all exceptions raised to avoid being bitten by the aforementioned bug.

Jack on Sep 6, 2009 10:34 PM

great blog, follow you!

Tarek on Nov 24, 2009 06:36 AM

Hi there I just want to know the way you make this window for coding. so it looks like .net framework

Visual C# Kicks on Jan 27, 2010 01:17 PM

Javascript exceptions are a pain in general

Gabriel McAdams on Feb 2, 2010 12:28 PM

I have just released code to help log JavaScript errors by sending error information to the server -
http://www.thecodepa....r-Notifications.aspx

ertert on Dec 1, 2010 03:37 AM


Ankitaa_luck on Sep 15, 2011 02:55 AM

Great article !!!!!!!!!!!!!!!!!
check out the following link for more details of javascript exception handling technique.

http://mindstick.com....ng%20in%20JavaScript

Thanks !

sponsored

MemtechLodhi on Sep 21, 2011 05:07 AM

Hi Guys,
A runtime error which causes to break the execution of a program is known as exception and mechanism to handle this exception so that program did not terminate abnormally is known as Exception handling........for more details check out the following link.......
http://mindstick.com....20in%20Java%20Script

Thanks !!!!!

Sourabh Bajaj on Sep 28, 2011 10:55 AM

Nice tutorial, Helpful and easy to learn. Good one.

berca on Feb 15, 2012 12:22 PM

C# Exception handling

http://csharp.net-in....sharp-exceptions.htm

merca.

Allan Ebdrup on Apr 8, 2012 03:39 PM

We've been building a SaaS solution for this for some time http://muscula.com. It works like google analytics, just copy a script to your page and you're logging.

We've found that the hardest part of having a great JavaScript error log is not logging the errors. There is a ton of other stuff you need to do. One big problem is that browsers log the errors very differently, so grouping them intelligently is very hard, we've spend months on this analyzing millions of JavaScript errors. Our algorithm is good now, but we've concluded that refinining this grouping logic will never be done. Another big problem with JavaScript error logs is all the noise generated from browser plugins. They account for 10-20% of all errors logged. Building our relevance filter that filters all this noise away has been a big task to. And then there is stuff like prettyprinting minified JavaScript when you show the location of the error in the code, integration with GA and more.

We log in more advanced ways than just onerror to get real call stacks and more information, but compared to not logging at all, a homebrewed solution that logs onerror is great. I highly suggest to anyone to log these errors, you'll be surprised at how many errors actually occur.

We're in private beta at the moment, but working very hard on launching.

kl;' on Feb 15, 2013 12:42 AM


Dumitru Glavan on May 26, 2013 08:55 AM

It's a bit more complex to log the clientside errors, supporting all the major browsers and mobile devices. We built http://jslogger.com to take care about that. It's also possible to log the backend errors with the NodeJS library. Worth to give it a try.

Leave a comment