throw (Statement)

Throw a custom exception in the hope it will be caught by an error handler.

Availability:

ECMAScript edition - 3
JavaScript - 1.5
JScript - 5.0
Internet Explorer - 5.0
Netscape - 6.0

The throw statement provides a way to create an exception which will be passed to an associated catch() handler in a try ... catch structure. It is really intended to be used in that context, but you can use it outside of a try ... catch structure and trap the exception with the normal onError event handling support.

You can use this mechanism to generate an error, perhaps as a result of testing some value. Placing a throw statement into your code will force the error handling to be invoked. However if you use it outside of a try ... catch block, the browser error handling will generate an error due to there being no way of catching the thrown event. It forces an error dialog, but not the one you wanted. You need to use a throw with a try ... catch block to force the catch code to be called.

You can work around this by assigning an error handler function to the onerror property and making sure that the error handler returns a Boolean true value to signify that the error has no further processing required.

Warnings:

Example code:

   <HTML>
   <HEAD>
   </HEAD>
   <BODY>
   <SCRIPT>
   // Define an error handler function
   function myErrHandler(anException)
   {
      alert("An error happened and was caught by this handler.");
      return true;
   }
   
   // Register the error handler
   onerror = myErrHandler;
   
   // Throw an exception
   throw "ERR";
   </SCRIPT>
   </BODY>
   </HTML>

See also:catch( ... ), Error object, EvalError object, Exception handling, finally ..., RangeError object, ReferenceError object, SyntaxError object, try ... catch ... finally, TypeError object, URIError object

Cross-references:

ECMA 262 edition 2 - section - 7.4.3

ECMA 262 edition 3 - section - 7.5.2

ECMA 262 edition 3 - section - 12.13