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]
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 ...