JScript .NET, Part XII: Exception Handling: The Error Object - Doc JavaScript | WebReference

JScript .NET, Part XII: Exception Handling: The Error Object - Doc JavaScript


JScript .NET, Part XII: Exception Handling

The Error Object

So far, we've thrown strings as exceptions. We threw "Error 325 from inner try block" for example. JScript .NET supports a more structured exception: the Error object. An Error object is thrown by the system whenever there is a run-time error. You can throw your own Error objects, and thus keep all exceptions of the Error type. You create Error objects with the Error constructor:

function Error([number : Number [, description : String ]])

where:

  • number is a numeric value assigned to the exception. It is optional.
  • description is a brief string that describes the exception. It is optional.

You can create a new Error object, populate it, and throw it, all in the same statement. For example:

throw new Error(35,"null object, call your vendor");
Here is a try...catch statement example:

try {
  throw new Error(35,"null object, call your vendor");
} 
catch(e) {
  print("e is: " + e)
  print("e.number is: " + (e.number & 0xFFFF));
  print("e.description is: " + e.description);
  print("e.name is: " + e.name);
  print("e.message is: " + e.message);
}

Notice the four properties of the Error object: number, description, name, and message. The description property is identical to the message property. The duplication is for historic reasons, and from the need to comply with the ECMA standard. The name property is Error, and the number property is the number assigned to the object during construction.

Notice that we bit-anded the number property with the 16-bit all-one word. The higher order word may contain different information such as the facility code. The Error number property is saved in the lower 16-bit word.

You should also take notice that Error is not a .NET framework type. If you need to share your JScript .NET module with other languages, you'd better use the System.Exception type.

Put the example above in a file, say error.js, compile and run it. You should get the following Command Prompt window:


Next: A Final Word


Produced by Yehuda Shiran and Tomer Shiran
All Rights Reserved. Legal Notices.
Created: September 9, 2002
Revised: September 9, 2002

URL: https://www.webreference.com/js/column118/6.html