Javascript Help: Error Handling Using Try and Catch

Client-side script like JavaScript can be notorious for failing. Even the best planned scripts can be hobbled by unanticipated DOM conditions. Some common problems?, a user with a non-standard, or outdated browser like Netscape Navigator 4 (NN 4) or Internet Explorer 3 (IE 3).

When something unexpected occurs, it often manifests itself as an error, and reflects badly on the script or web page author ...even when it's the visitor's nappy browser that is to blame. Some care can and should be taken to combat these scenarios. It is possible to plan for unforeseen problems, and try to mitigate code risks. For example, if you are using a method that may or may not exist, test for it first. Consider that many older browsers don't support document.getElementById(). As an author, you shouldn't penalize the masses for the misdirection of the few. Instead, write with the expectation that a visiting browser will support getElementById, but test for it such as if(document && document.getElementById){ obj = document.getElementById('someObject') }. Doing this gives you the opportunity to control error flow.

Unfortunately, sometimes you need a broader error trapping mechanism. In JavaScript 1.3 error handling became a part of the language. The commands try, catch, and throw became available as a mechanism not for preventing an error, but for handling the failure in a controlled way and then permitting subsequent script to continue running if you wish.

The following example shows a simplified error scenario. The two form buttons below each call separate functions ("methods" of the window object in this case). Those functions in turn try to call a non-existent method. In the default case (the one with no error handling) the failure will manifest itself in the form of a small error icon appearing in the bottom left corner of IE, or in the javascript console for Mozilla.

Note: Most developers change the default IE settings, by checking the box next to "Display a notification about every script error" in the Tools -> Options -> Advanced tab of their browsers. This results in a big nasty alert style popup which interferes with the interface by stealing focus and control from the document... and makes your page (and js programming) look poorly conceived.

Tip: Most developers use the terms method, function and subroutine interchangably. Though subroutine isn't generally in the JavaScript lexicon. As I understand it, the term method came about as part of the Object Oriented Programming (OOP) movement to express a behavior of some abstracted type (i.e. "This thing can -DO- this action"), and has (for better or worse) flowed back into general programming grammar. Aside: The Pascal programming language used the term subroutine and reserved the term function to identify a subroutine which returned a value. (Perl uses the term subroutine too, though may not make the same distinction as Pascal). So basically... function, method (and if you hear it in discussions, subroutine) are all flavors of the same basic construct.

The function which uses error handling will also experience the same error which occurs in the default non-error handling function. However, in it's case, because the expression is wrapped in a try{ } block, the browser should pass control to the corresponding catch(){ } block and permit statements within that block to continue executing, allowing you to recover from the error more gracefully hopefully. Note that the error handling function permits the execution to continue even outside of the scope of the function which failed. In this case, the sequence goes as follows...

button pressed -> error handling function called -> warning about upcoming failure -> !! FAILURE !! -> expose method expresses internals of the error object -> function returns a string -> the surrounding alert method runs and displays the string returned by the error handling function.

Contrast this with the default / non-error handling scenario, whose sequences is as follows...

button pressed -> non-error handling function called -> warning about upcoming failure -> !! FAILURE !! (execution stops at that point... meaning the function does NOT pass back its return string, and the surrounding alert DOES NOT run.)

Error Results:

Related Keywords: javascript, error, handling, try, catch, throw, client-side, script