↑
Main Page
Error objects
throw new URIError(“Uri, is that you?”);
throw new ReferenceError(“You didn’t cite your references properly.”);
Practically speaking, an error would be thrown in a situation where normal execution could not con-
tinue, such as this:
function addTwoNumbers(a, b) {
if (arguments.length < 2) {
throw new Error(“Two numbers are required.”);
} else {
return a + b;
}
}
In the previous code, the function requires two numbers to execute properly. If two arguments are not
passed in, the function throws an error indicating that the calculation cannot be completed.
Developer-thrown exceptions are caught inside of
try...catch
statements just like an error thrown by
the browser itself. Consider the following code, which catches a developer-thrown exception:
function addTwoNumbers(a, b) {
if (arguments.length < 2) {
throw new Error(“Two numbers are required.”);
} else {
return a + b;
}
}
try {
result = addTwoNumbers(90);
} catch (oException) {
alert(oException.message); //outputs “Two numbers are required.”
}
Additionally, because browsers don’t generate
Error
objects (they always generate one of the more spe-
cific
Error
objects, such as
RangeError
), it is easy to differentiate between an error thrown by the
developer and one thrown by the browser using either one of the techniques discussed earlier:
function addTwoNumbers(a, b) {
if (arguments.length < 2) {
throw new Error(“Two numbers are required.”);
} else {
return a + b;
}
}
try {
result = addTwoNumbers(90, parseInt(“z”));
} catch (oException) {
if (oException instanceof SyntaxError) {
alert(“Syntax Error: “ + oException.message);
} else if (oException instanceof Error) {
alert(oException.message);
}
}
427
Error Handling
17_579088 ch14.qxd 3/28/05 11:41 AM Page 427
Free JavaScript Editor
Ajax Editor
©
→