This section provides a quick description and a tutorial example script on the 'Error' built-in object type, which is used to create 'Error' objects for runtime exception handling.
The "Error" object type is a built-in object type to be used to create a "Error" object,
representing a runtime exception. It has the following main features:
New "Error" objects can be created with the "Error()" constructor.
"Error()" can also be used as a regular function, which also returns an "Error" object.
All "Error" objects have 2 inherited properties: name and message.
All "Error" objects have the common inherited method: toString().
The "Error" object type has many sub types: EvalError, RangeError, ReferenceError, SyntaxError, TypeError, and URIError.
Here is a tutorial example script showing some of the those features:
// Error_Object_Type.html
// Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
// Creating a new Error object
var myObject = new Error("Too many users on herongyang.com");
// Checking this object
println("\nAbout this \"myObject\":");
println(" Type = "+(typeof myObject));
println(" Instance Of Object: "+(myObject instanceof Object));
println(" Instance Of Error: "+(myObject instanceof Error));
// Throw my dummy error and catch it
try {
// If # sessions on site > 100
throw myObject;
} catch (myError) {
println("\nAbout this \"myError\":");
println(" Type = "+(typeof myError));
println(" Instance Of Error: "+(myError instanceof Error));
println(" myError.name: "+myError.name);
println(" myError.message: "+myError.message);
}
// Catch a real error
try {
var o = null;
o.toString();
} catch (realError) {
println("\nAbout this \"realError\":");
println(" Type = "+(typeof realError));
println(" Instance Of Error: "+(realError instanceof Error));
println(" realError.name: "+realError.name);
println(" realError.message: "+realError.message);
}
If you run this script with "jrunscript", you will get:
About this "myObject":
Type = object
Instance Of Object: true
Instance Of Error: true
About this "myError":
Type = object
Instance Of Error: true
myError.name: Error
myError.message: Too many users on herongyang.com
About this "realError":
Type = object
Instance Of Error: true
realError.name: TypeError
realError.message: Cannot call method "toString" of null
Now we know how to create "Error" objects with the "Error()" constructor.
Read other "Error" related chapters to see more tutorial examples.