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
messageAn optional description of the error.

Class Properties

Class Property Description
prototypeEnables property assignment to objects of type Error.

Instance Properties

Instance Property Description
constructorReturns a reference to the Error function that created the prototype.
messageAn error message.
nameAn 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);
}  

Press the button below to action the above code:


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!');
}   

Press the button below to action the above code:


Related Tutorials

JavaScript Advanced Tutorials - Lesson 2 - Errors

go to home page Homepage go to top of page Top