↑
Main Page
Determining the type of error
Determining the type of error
Despite being limited to only one
catch
clause per
try...catch
statement, you have a couple of easy
ways to determine the type of error that was thrown. The first is to use the
name
property of the
Error
object:
try {
eval(“a ++ b”); //causes SyntaxError
} catch (oException) {
if (oException.name == “SyntaxError”) {
alert(“Syntax Error: “ + oException.message);
} else {
alert(“An unexpected error occurred: “ + oException.message);
}
}
The second way is to use the
instanceof
operator and use the class name of different errors:
try {
eval(“a ++ b”); //causes SyntaxError
} catch (oException) {
if (oException instanceof SyntaxError) {
alert(“Syntax Error: “ + oException.message);
} else {
alert(“An unexpected error occurred: “ + oException.message);
}
}
Raising exceptions
The third edition of ECMAScript also introduced the
throw
statement to raise exceptions purposely. The
syntax is the following:
throw
error_object
;
The
error_object
can be a string, a number, a Boolean value, or an actual object. All the following
lines are valid:
throw “An error occurred.”;
throw 50067;
throw true;
throw new Object();
It is also possible to throw an actual
Error
object. The constructor for the
Error
object takes only one
parameter, the error message, making it possible to do the following:
throw new Error(“You tried to do something bad.”);
All the other classes of
Error
are also available to developers:
throw new SyntaxError(“I don’t like your syntax.”);
throw new TypeError(“What type of variable do you take me for?”);
throw new RangeError(“Sorry, you just don’t have the range.”);
throw new EvalError(“That doesn’t evaluate.”);
426
Chapter 14
17_579088 ch14.qxd 3/28/05 11:41 AM Page 426
Free JavaScript Editor
Ajax Editor
©
→