Error
object constructorS2C Home « Globals « Error
In JavaScript you create an error instance using the constructor Error
.
Description
Creates a generic Error
object, this is created by JavaScript automatically when runtime errors are encountered.
Syntax
Signature | Description |
---|---|
anError = new Error([message]); | Creates a generic Error object, this is created by javaScript automatically when runtime errors are encountered. |
Parameters
Parameter | Description |
---|---|
message | An optional description of the error. |
Class Properties
Class Property | Description |
---|---|
prototype | Enables property assignment to objects of type Error . |
Instance Properties
Instance Property | Description |
---|---|
constructor | Returns a reference to the Error function that created the prototype. |
message | An error message. |
name | An error name. |
Class Methods
None.
Instance Methods
By using methods of the Error
object we can also access elements of errors, manipulate errors after creation and even create new errors from existing errors.
Instance Method | Description |
---|---|
Getter (Accessor) MethodsThese methods DO NOT modify the Error object |
|
toString() | Returns a string representation of the specified Error object. |
Setter (Mutator) MethodsThese methods DO modify the Error object |
|
None. |
Examples
Let's look at some examples of throwing an error within our code.
// Throw an error.
try {
throw new Error();
} catch (e) {
alert('An error: ' + e.name);
}
// Throw an error with a message.
try {
throw new Error('Throwing an error.');
} catch (e) {
alert('An error with message: ' + e.name + ': ' + e.message);
}
We can also create our own Error
instances as the example below shows.
// Create our own Error object.
function ourError(message) {
this.name = 'OurError';
this.message = message || 'Default Message Used When No Message Passed';
}
// Inherit from the Error prototype.
ourError.prototype = new Error();
ourError.prototype.constructor = ourError;
// Throw an error.
try {
throw new ourError();
} catch (e) {
alert('Our Error: ' + e.name + ' Message: ' + e.message);
}
// Throw an error and a message.
try {
throw new ourError('A Message we have passed');
} catch (e) {
alert('Our Error: ' + e.name + ' Our Message: ' + e.message);
} finally {
alert('A finally statement will always be executed!');
}
Related Tutorials
JavaScript Advanced Tutorials - Lesson 2 - Errors