Graceful error handling in JavaScript

JavaScript provides rudimentary support for error handling to properly handle and avoid errors. Learn about the various techniques available to help you address any development problems you might encounter.

Regardless of your skill level, errors or exceptions are a fact of life for application developers. The disconnected nature of Web development leaves many points where errors can and do occur. The key is gracefully handling any unexpected (or expected) errors to control the user experience. With JavaScript, there are various techniques available, as well as language features, to properly handle any problems.

Check everything

A good programming practice is to check everything before proceeding. That is, you should check the validity of an object, method call, and so forth before utilizing them. This avoids any errors associated with working with an object that has not been instantiated or a call to a method that does not exist. Listing A checks for objects used (variables and fields) before using them. The script makes sure field objects are not null or empty before working with them.

You don't have to actually include the check for null—you can simply use the object in the if statement, and it evaluates to true if it is not null. Listing B uses this syntax and the getElementByID method as well. It uses an if statement to ensure the getElementByID method is supported (exists) before continuing.

While checking objects before using them is a good approach, errors still appear from time to time. In these instances, the JavaScript language makes it easy to catch these errors and continue accordingly.

Weekly development tips in your inbox
Keep your developer skills sharp by signing up for TechRepublic's free Web Development Zone newsletter, delivered each Tuesday.
Automatically sign up today!

Catching errors

Similar to other languages like Java and C#, JavaScript includes the try/catch/finally statement. A try statement encloses a block of code in which an exception, like a runtime error, may occur. The catch clause outlines how the error will be handled, and the finally block includes code that is always executed.

Basically, the code tries to execute a block of code and control is passed to the catch block if it does not execute successfully. The catch block is skipped if no errors occur. The finally block executes after the try and catch blocks finish. It has the following syntax:

// code
// code
// code

The catch and finally blocks are optional, but not including the catch block doesn't make sense. Consider Listing C for demonstrating try/catch/finally usage. It generates an error since the referenced field does not exist on the form.

A try/catch block can't avoid the error, but it can gracefully handle it so a user isn't confronted with an obscure browser error message. View Listing D.

It produces the following message, but the finally block ensures the form is submitted—regardless of any errors that may occur.

An unexpected error has occurred.

Please contact the administrator.

'document.forms.0.firstName.value' is null or not an object

A single catch block can process all problems, but multiple catch statements may be used to process specific errors. It is covered in the next section.

Throwing errors

Unexpected errors are easily handled with try/catch statements. In some instances, you may wish to handle errors differently. JavaScript provides the throw statement. Its syntax is basic—throw followed by the exception to generate. This allows you to define and throw custom exceptions. The code in Listing E creates an exception for missing values, and it is generated.

The following message is displayed (if no value is entered in the field):

An unexpected error has occurred.
Please contact the administrator.
First name is missing.

In addition, you may use the instanceof operator to determine the exception type and react accordingly. The code in Listing F checks the exception object's type and displays related data accordingly.

The instanceof operator may be used in conjunction with standard errors. JavaScript defines the following standard JavaScript error types:

  • EvalError: signals the global eval function was used incorrectly.
  • RangeError: indicates a numeric value has exceeded its allowable range of values.
  • ReferenceError: an illegal reference has been detected.
  • SyntaxError: a parsing error occurred.
  • TypeError: the actual type of an operand is different than its expected type.
  • URIError: one of the global URI functions (encodeURI or decodeURI) was used incorrectly.

The code in Listing G uses the TypeError type in a catch statement. A type error is generated by the extra d in the line referencing the field name (ddocument).

Handling all page errors

Another feature at your disposal is the window.onerror event. Like all other JavaScript events, you can define a function or piece of code to be run when the event is triggered. It can be used to handle or ignore errors. The page in Listing H displays a simple message for all JavaScript errors encountered. The error is generated when the button is clicked since the specified function does not exist. The code in Listing I uses the onerror event to ignore all errors.

An issue with the onerror event is browser support. The biggest culprit has been within the Opera browser, so you should verify that all target browsers support this feature before integrating it into your application.

Handle with care

Errors are a part of every application, but proper error handling is not. Proper usage of JavaScript's error handling features and smart coding can smooth the user experience, as well as ease diagnosis on the development end.

Miss a column?

Check out the Web Development Zone archive, and catch up on the most recent editions of Tony Patton's column.

Tony Patton began his professional career as an application developer earning Java, VB, Lotus, and XML certifications to bolster his knowledge.

About Tony Patton

Tony Patton has worn many hats over his 15+ years in the IT industry while witnessing many technologies come and go. He currently focuses on .NET and Web Development while trying to grasp the many facets of supporting such technologies in a productio...

Editor's Picks

Free Newsletters, In your Inbox