Generates an error condition that can be handled by a try...catch...finally statement.
throw [exception] |
Arguments
- exception
-
Optional. Any expression.
Remarks
The throw statement can be used without an argument, but only if the throw statement is contained within a catch block. In that situation, the throw statement re-throws the error caught by the enclosing catch statement. When an argument is provided, the throw statement throws the value of exception.
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...finally statements:
В | Copy Code |
---|---|
function TryCatchDemo(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 a handled error. return(e + " handled locally."); // Return 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 + " error handled higher up."); // Return error message. } } print(TryCatchDemo(0)+ "\n"); print(TryCatchDemo(1)); |