JavaScript: The Definitive GuideJavaScript: The Definitive GuideSearch this book

6.16. throw

An exception is a signal that indicates that some sort of exceptional condition or error has occurred. To throw an exception is to signal such an error or exceptional condition. To catch an exception is to handle it -- to take whatever actions are necessary or appropriate to recover from the exception. In JavaScript, exceptions are thrown whenever a runtime error occurs and whenever the program explicitly throws one using the throw statement. Exceptions are caught with the try/catch/finally statement, which is described in the next section.[21]

[21]The JavaScript throw and try/catch/finally statements are similar to but not exactly the same as the corresponding statements in C++ and Java.

The throw statement has the following syntax:

throw expression; 

expression may evaluate to a value of any type. Commonly, however, it is an Error object or an instance of one of the subclasses of Error. It can also be useful to throw a string that contains an error message, or a numeric value that represents some sort of error code. Here is some example code that uses the throw statement to throw an exception:

function factorial(x) {
    // If the input argument is invalid, thrown an exception!
    if (x < 0) throw new Error("x must not be negative");
    // Otherwise, compute a value and return normally
    for(var f = 1; x > 1; f *= x, x--) /* empty */ ;
    return f;
} 

When an exception is thrown, the JavaScript interpreter immediately stops normal program execution and jumps to the nearest exception handler. Exception handlers are written using the catch clause of the try/catch/finally statement, which is described in the next section. If the block of code in which the exception was thrown does not have an associated catch clause, the interpreter checks the next highest enclosing block of code to see if it has an exception handler associated with it. This continues until a handler is found. If an exception is thrown in a function that does not contain a try/catch/finally statement to handle it, the exception propagates up to the code that invoked the function. In this way, exceptions propagate up through the lexical structure of JavaScript methods and up the call stack. If no exception handler is ever found, the exception is treated as an error and is reported to the user.

The throw statement is standardized by ECMAScript v3 and implemented in JavaScript 1.4. The Error class and its subclasses are also part of ECMAScript v3, but they are not implemented until JavaScript 1.5.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.