How to throw an exception in Javascript

For robust error handling in Javascript it is best to throw exception objects and catch them if needed in the calling code. To throw an exception the following code can be used.

throw new Error("message");

A single parameter is required for the creation and throwing of the exception in the above code; just the error message string which is usually the reason for the error.

The code below shows how the exception can be thrown and caught in Javascript:

try{
  throw new Error("foo");
}
catch(e){
 alert(e.name + "\\n" + e.message)
}

Once the exception is caught you have access to its two properties: Firstly the name of the error, which is actually the name of the constructor function that created the exception object. Secondly the error message which was provided when the exception object was created.

Last updated: 16/02/2012