Handling Errors - Java Script

Understanding errors is just part of the solution; understanding how to handle those errors is the other part.Instead of using multiple if..else statements,JavaScript offers two specific ways to handle errors.The Browser Object Model includes the onerror event handler on both the window object and on images,whereas ECMAScript defines the try...catch construct, another statement borrowed from Java, to deal with exceptions. This section outlines the advantages and disadvantages of each approach.

The onerror event handler

The onerror event handler was the first feature to facilitate error handling for JavaScript.The error event is fired on the window object whenever an exception occurs on the page.Example:

In this example, an exception occurs when an attempt is made to call nonExistentFunction(),which doesn’t exist. When this happens, the alert is displayed containing the message,“An error occurred.” Unfortunately, the browser’s error message is also displayed.To hide the error from the browser (and thus prevent it from reporting the error), the onerror event handler must return a value of true:

Extracting error information

Simply knowing that an error occurred is of little use to a programmer without the error details. Fortunately,the onerror event handler provides three pieces of information to identify the exact nature of the error:

  1. Error message — The same message that the browser would display for the given error
  2. URL — The file in which the error occurred
  3. Line number — The line number in the given URL that caused the error

This information is passed as three parameters into the onerror event handler and can be accessed like this:

Using this code,it is possible to create custom JavaScript error dialogs that mimic the functionality of browser-error dialogs.

Image loading errors

The window object isn’t the only one that supports the onerror event handler; images do too. When an image fails to load for any reason (for example, the file does not exist),the error event fires on the images. You can set the onerror event handler for an image either in HTML or through script. For example:

This example assigns the onerror event handler directly in the HTML.Because the image “blue.gif” doesn’t exist,the alert is displayed letting the user know the image didn’t load completely.In order to assign the event handler using a script, you must wait until after the page has loaded before setting the image’s src attribute:

In this example, the first image isn’t assigned an src attribute in the HTML. When the page is loaded, however,the image is first assigned an onerror event handler and then has its src property set to “blue.gif”,which doesn’t exist. The alert displays once again,indicating the image didn’t load.

Handlingsyntax errors

The onerror event handler isn’t just good for dealing with exceptions; it is also the only way to deal with syntax errors.

To do so,the event handler must be the first code that appears in the page. Why the first? If a syntax error occurs before the event handler has been set up,that event handler will never be set up. Remember,a syntax error completely stops code execution. Consider the following example:

Because the highlighted line(which is a syntax error) occurs before the onerror event handler is assigned,the browser reports the error directly. The code immediately following the error is not interpreted (because the thread is exited) so when the load event fires and the nonExistentFunction() is called, the browser reports that error as well. If this page is rewritten to place the onerror event-handler assignment before the syntax error, two alerts are displayed: one showing the syntax error and one showing the exception.

The try...catch statement

ECMAScript,third edition,introduced another feature from Java, the try...catch statement for browsers that support ECMAScript 3 (“What Is JavaScript?”).The basic syntax is the following:

For example:

While running a try...catch statement, the interpreter first enters the code block immediately after the try keyword. In the previous example, the line window.nonExistantFunction(); is executed, which causes an error (because no method named nonExistantFunction exists for the window object). At that point, execution immediately exits the try clause and goes into the catch clause, completely skipping over any further lines of code (the alert(“Method completed.”); line is skipped). The alert in the catch clause is displayed, and then execution moves into the finally clause to display that alert.

Unlike Java, the ECMAScript standard specifies only one catch clause per try...catch statement. Because JavaScript is only loosely typed, you have no way to specify a particular type of exception in the catch clause. All errors,regardless of type, are handled by a single catch clause.

The code in the finally clause behaves the same way as the finally clause in Java,containing code that should be executed whether or not an exception occurs.This is useful for closing open connections and freeing up resources.For instance:

Nested try...catch statements

It is possible for an error to occur inside the catch clause of a try...catch statement.In this case, using nested try...catch statements is the answer. Consider the following example

In this example, an error is thrown immediately and the first alert is displayed. When execution continues in the first catch clause, another error is thrown because of the attempt to create an array with too many elements. Execution goes to the second catch clause and displays the second alert before continuing on into the finally clause.

The Error object

So what exactly is it that the catch statement catches? Just as Java has a base class Exception to throw, JavaScript has a base class called Error to throw.An Error object has the following properties:

  • name — A string indicating the type of error
  • message — The actual error message

The name of the Error object corresponds to its class (because Error is just a base class), which is one of the following:

The Error object

The message property of an Error object is the browser-generated error message indicating the nature of the error. Because this property is browser-specific,the same error can generate a different error message in different browsers.Consider the following line of code:

eval(“a ++ b”);

This line alone causes a SyntaxError to be thrown because the ++ symbol isn’t valid in this context.The error message from Internet Explorer 6 is “Expected ‘;’” whereas Mozilla 1.5 provides “missing ; before statement.”

The message property can be used to display a more meaningful message to users while preventing the browser from reporting the error directly:

Determining the type of error

Despite being limited to only one catch clause per try...catch statement,you have a couple of easy ways to determine the type of error that was thrown.The first is to use the name property of the Error object:

The second way is to use the instanceof operator and use the class name of different errors:

Raising exceptions

The third edition of ECMAScript also introduced the throw statement to raise exceptions purposely. The syntax is the following:


The error_object can be a string,a number,a Boolean value, or an actual object. All the following lines are valid:

It is also possible to throw an actual Error object. The constructor for the Error object takes only one parameter, the error message, making it possible to do the following:

throw new Error(“You tried to do something bad.”);

All the other classes of Error are also available to developers:

Practically speaking, an error would be thrown in a situation where normal execution could not continue, such as this:

In the previous code, the function requires two numbers to execute properly. If two arguments are not passed in, the function throws an error indicating that the calculation cannot be completed.

Developer-thrown exceptions are caught inside of try...catch statements just like an error thrown by the browser itself. Consider the following code, which catches a developer-thrown exception:

Additionally, because browsers don’t generate Error objects(they always generate one of the more specific Error objects, such as RangeError), it is easy to differentiate between an error thrown by the developer and one thrown by the browser using either one of the techniques discussed earlier:

Note that the check for the instanceof Error must be the last condition in the if statement because all the other error classes inherit from it (so a SyntaxError returns true when testing instanceof Error).

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Java Script Topics