Main Page

Error Handling

Error Handling
Traditionally, JavaScript has been known as a language filled with confusing error messages such
Object Expected
Illegal Syntax
with nothing more than a line number to identify its origin.
Debugging such messages was a painful experience at best, which is why the version 4 browsers
(Internet Explorer 4.0 and Netscape Navigator 4.0) included some basic error-handling functional-
ity. Shortly thereafter, an answer came from the ECMA in the form of ECMAScript, third edition.
This latest edition of ECMAScript added exception handling capabilities modeled after its big
brother, Java. Using some of the reserved words from the second edition of ECMAScript, the third
edition implements the
construct as well as the
This chapter explores both the browser-based error-handling capabilities as well as ECMAScript’s
exception-handling features.
The Importance of Error Handling
In early browsers (such as Internet Explorer 3.0 and Netscape Navigator 3.0), there was no error
handling. Typically, functions return an
value (often
, or –1, depending on the
use case) to indicate that an error has occurred. Consider the following code:
var iLoc = findItem(colorarray, “blue”);
if (iLoc == -1) {
alert(“The item doesn’t exist. “);
} else {
alert(“The item is in location “ + iLoc + “.”);
In this case, the function
returns a –1 (an invalid value) when the given string doesn’t
exist. Presumably, a valid value is a number greater than or equal to 0. But why did the function
return the invalid value? Does the string
simply not exist in
? Or is there
17_579088 ch14.qxd 3/28/05 11:41 AM Page 411

JavaScript EditorFree JavaScript Editor     Ajax Editor