Main Page

Throwing your own errors

Throwing your own errors
One of the best ways to manage debugging and errors in JavaScript code is to throw your own errors.
Now, you may be thinking, “How do I reduce errors by causing errors?” The idea is that you throw spe-
cific errors that tell you exactly what error occurred instead of relying on JavaScript’s cryptic
error messages. Doing so can cut down debugging time dramatically. Consider a function
designed to divide one number by another:
function divide(iNum1, iNum2) {
return iNum1.valueOf() / iNum2.valueOf();
This function assumes several things. First, it assumes that two arguments are passed in; second, it
assumes that both arguments are numbers. But if you make a call that breaks these assumptions, such as
, you end up with an error message like
undefined’ is not an object
iNum2 has
no properties
. Add some specific error messages, and the problem becomes clear:
function divide(iNum1, iNum2) {
if (arguments.length != 2) {
throw new Error(“divide() requires two arguments.”);
} else if (typeof iNum1 != “number” || typeof iNum2 != “number”) {
throw new Error(“divide() requires two numbers for arguments.”);
return iNum1.valueOf() / iNum2.valueOf();
In this case, if you call
, you’ll get an error saying
divide() requires two arguments
if you call
divide(“a”, “b”)
, you get an error saying
divide() requires two numbers for
. In both cases, these messages give you much more information than the default JavaScript
error messages and make debugging much easier.
Because of the amount of code required to check for errors and throw messages, many developers create
their own
function. Many programming languages have an
method built-in, and
it’s also easy to create your own:
function assert(bCondition, sErrorMessage) {
if (!bCondition) {
throw new Error(sErrorMessage);
function simply tests to see if the first argument evaluates to
and, if so, throws an
error with the given error message. You can then use
like this:
function divide(iNum1, iNum2) {
assert(arguments.length == 2, “divide() requires two arguments.”);
assert(typeof iNum1 == “number” && typeof iNum2 == “number”,
“divide() requires two numbers for arguments.”);
return iNum1.valueOf() / iNum2.valueOf();
Error Handling
17_579088 ch14.qxd 3/28/05 11:41 AM Page 431

JavaScript EditorFree JavaScript Editor     Ajax Editor