JavaScript & jQuery Tutorials

JS Home Right Arrow JS Advanced Right Arrow Errors

Errors

Sometimes things go wrong in our code and an error is raised which we can deal with. Javascript has several predefined objects to deal with errors and the try....catch....finally and throw statements which give us some control over them. In this lesson we look at errors and how to handle them.

We can create our own error objects for specific purposes by prototyping the global Error object, thus giving us the opportunity to throw or catch errors tailored to our needs.

Examples

The throw statement allows us to throw an exception with an accompanying error message when required. The try....catch....finally construct allows us to wrap code that may throw an error and allow us to act on it.

Let's look at a couple of examples of creating our own Error object which we can throw errors on it.



// 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:


Other Global Error Objects

As well as the generic Error object JavaScript offers other error constructors tailored to specific errors.

RangeError - creates a RangeError instance that occurs when a numeric variable/parameter is outside its valid range.

ReferenceError - creates a ReferenceError instance when trying to dereference a non-existant variable.

TypeError - creates a TypeError instance that occurs when a variable/parameter is not of a valid type.

URIError - creates a URIError instance that occurs when URI handling functions are passed malformed URIs.


Lesson 2 Complete

In this lesson we looked at creating our own Error objects tailored to our needs. We also looked at the try....catch....finally construct and the throw statement.


What's Next?

In the next lesson we look at the Number global object and how to use it.


Reference

JavaScript Reference - Error constructor
JavaScript Reference - RangeError constructor
JavaScript Reference - ReferenceError constructor
JavaScript Reference - TypeError constructor
JavaScript Reference - URIError constructor
JavaScript Reference - throw statement
JavaScript Reference - try....catch....finally construct
JavaScript Reference - new special operator



  

go to home page Homepage go to top of page Top