JavaScript tutorial:
throw statement

 

The throw statement generates an error condition that can be handled by a try...catch statement.

Syntax

throw exception

The exception argument can be any expression.

Return value

None

Example

The following example throws an error based on a passed-in value, then illustrates how that error is handled in a hierarchy of try...catch statements:

function TryCatch(x) {
try {
try {
if (x == 0) // Evalute argument.
throw "x equals zero"; // Throw an error.
else
throw "x does not equal zero"; // Throw a different error.
}
catch(e) { // Handle "x = 0" errors here.
if (e == "x equals zero") // Check for an error handled here.
return(e + " handled locally."); // Return object error message.
else // Can't handle error here.
throw e; // Rethrow the error for next
} // error handler.
}
catch(e) { // Handle other errors here.
return(e + " handled higher up."); // Return error message.
}
}
document.write(TryCatch(0));
document.write(TryCatch(1));

To run the code, paste it into JavaScript Editor, and click the Execute button.

See also: try...catch statement