TypeError constructor JS Home  <<  JS Reference  <<  TypeError

In JavaScript you create a TypeError instance using the constructor TypeError.

Description

Creates a TypeError object when a variable or parameter is not of a valid type.

Syntax

Signature Description
anError = new TypeError([message]);Create a TypeError instance using the constructor TypeError.

Parameters

Parameter Description
messageAn optional description of the error.

Class Properties

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

Instance Properties

Instance Property Description
constructorReturns a reference to the TypeError function that created the prototype.
nameAn error name.

Class Methods

None.

Instance Methods

None.

Examples


Let's look at some examples of throwing a type error within our code.


// Throw an error.
try {
  throw new TypeError();
} catch (e) {
    alert('A type error: ' + e.name);
}  

// Throw an error with a message.
try {
  throw new TypeError('Throwing a type error.');
} catch (e) {
    alert('A type error with message: ' + e.name + ': ' + e.message);
}  

Press the button below to action the above code:

We can also create our own TypeError instances as the example below shows.



// Create our own TypeError object.
function ourTypeError(message) {  
  this.name = 'OurTypeError';  
  this.message = message || 'Default Message Used When No Message Passed';
}   

// Inherit from the TypeError prototype.
ourTypeError.prototype = new TypeError();  
ourTypeError.prototype.constructor = ourTypeError;   

// Throw an error.
try {  
  throw new ourTypeError();  
} catch (e) {  
  alert('Our Error: ' + e.name + ' Message: ' + e.message);
}   

// Throw an error and a message.
try {  
  throw new ourTypeError('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