Export (0) Print
Expand All

throw Statement 

Generates an error condition that can be handled by a try...catch...finally statement.


throw [exception]

exception

Optional. Any expression.

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.

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:

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));

Community Additions

ADD
Show:
© 2014 Microsoft