Catching errors before they catch you

Jake Howlett, 16 September 2001

Category: JavaScript; Keywords: try catch exception error

Wouldn't a developer's life be easy if there were never any errors in it. Or would it? Might get a bit boring after a while if there was never that buzz of finally finding the source of your woes after hours pulling at your hair. No matter what your outlook, as professionals we should always try our best to avoid them ever happening.

Obviously we can't guarantee they will never happen. What we can do though is make sure that when they do it is as painless as possible for the user. If that user also happens to be a customer then this becomes even more important.

Handling errors:

Internet Explorer 5 and Netscape 6 have introduced Exception handling to their JavaScript implementations. This means that we can see when an error has occurred and deal with it accordingly. Let's see how:

function notVeryWellDesigned( foo ){
try
{
Alert( foo );
}
catch (exception)
{
if (exception.description == null) {
alert("Exception: " + exception.message);
}
else
{
alert("Exception: " + exception.description);
}
}
}
Being a fool I have accidentally typed alert with a capital A. Being case-sensitive, JavaScript isn't going to like this. See what your browser thinks of it here.

Did it "work" for you? Let's have a look at what you should have seen anyway.

Here's Opera 5 being verbose:

image

Here's Netscape 6 being unusually helpful:

image

And finally Internet Explorer in cryptic mode:

image

Putting it in to practice:

The above example isn't ideal. After all, you wouldn't expect something as obvious as this ever to get out of development. A better example would be a script that relies on user input to perform its task. This is where we are likely to see more errors.

How and where you use these try and catch routines is obviously down to you and your situation. Personally I would only use them when there is cause for concern that an error may occur. For example if you are using JavaScript to talk to an applet like the R5 View Applet and the applet hasn't load properly/completely you will generate errors. In this case it is useful to tell the code to try again later. Here's a script that does that:
function tryAndGetNameOfViewInApplet()
{
alert(document.applets.view.getViewName());
}
catch (exception)
{
window.status="Waiting for view\'s applet to load...";
setTimeout("tryAndGetNameOfViewInApplet()",500);
}
So there you go. You can now make your web applications handle problems a lot more gracefully and keep your professional integrity whilst your at it....

Note: This is not supported in the version of JavaScript that Notes implements. This means that you can't type these function in to the JS Header element of a page of form. Instead you will either have to add it directly to the form or turn OFF "Enable JavaScript" in the Notes Client user preferences. Beware the obvious consequences though.