Exception Handling in Client-Side Web Development

Table of Contents



Overview

A Web developer will encounter three types of errors while building client-side Web pages.

Of the three general error types, only the run-time errors will require exception handling. Syntax errors are detected by the interpreter and the code is not executed. Logic errors will produce undesirable results but may not generate a run-time error. A run-time error will normally impact the user unless the developer anticipates and designs a recovery for the exception.

Following are the technologies that are typically employed for client-side Web development:

The markup languages, style sheets and the DOM are eliminated from this discussion on exception handling because:

Your errant markup and style will certainly cause anomalies in the presentation of your content, but they should never cause a run-time error.

Therefore, our discussion on exception handling in the client-side Web development environment is limited to JavaScript and the BOM technologies. To be more specific, the features we will review are:

JavaScript: Error Object

When an exception in JavaScript is thrown, the relevant information about the exception is stored in an Error object. There exists a generic Error class and several specific subclasses named below. All versions of the error object(s) have two properties that are supported by ECMAScript.

Note that different browser implementations support other properties. Other properties unique to a specific browser are: description (IE), fileName (Mozilla), lineNumber (Mozilla), number (IE) and stack (Mozilla). At present, we will work with the two properties (name and message) that are supported by most current version browsers and are part of the ECMA-262 standard.

The safe way to create an instance of an exception of the generic Error class is to create an instance with the new constructor and then assign needed values to the properties.

var userError = new Error(); // assign the properties as needed userError.message = "Invalid syntax for prompt"; userError.name = "SyntaxError";

You can also create instances of the specific type exceptions given in the name property. These objects are subclasses to the generic Error class. The subclasses all have the same properties (name and message) as were defined above for the generic Error class. The argument to the constructor is the message property.

var evalException = new EvalError("illegal use of eval function"); var rangeException = new RangeError("array length error"); var refException = new ReferenceError("the variable does not exist"); var syntaxException = new SyntaxError("syntax error found in eval method"); var typeException = new TypeError("value is not number type"); var URIException = new URIError("decoding error");

If you want additional detail on the above Error objects, consult our table of links below:

A Summary of JavaScript Error Classes
Error Class Type Members
Common to all Error Classes
Short Description
 
Error Super Class Property: message
Property: name
Method: toString
a generic exception
EvalError SubClass thrown when incorrect usage of eval() function
RangeError SubClass thrown when a number is not in valid range
ReferenceError SubClass thrown when a variable does not exist
SyntaxError SubClass thrown to signal a syntax error
TypeError SubClass thrown when value is of the wrong type
URIError SubClass thrown by URI encoding or decoding methods



JavaScript: throw Statement

We learned from the above topic that the browser will throw an exception when a run-time error occurs. The browser creates an Error object and reports the exception to the user via a message of some sort (the message reported varys depending on the browser).

A good programming practice is to minimize or eliminate any user involvement when exceptions occur. The JavaScript programmer can accomplish this by anticipating and capturing the run-time exceptions. He accomplishes this with two tools provided with core JavaScript. They being the try/catch statement and the throw statement. These two statements work together. That is, the try statement can throw the details of a run-time error and catch the error event for clean-up and/or recovery processing.

The throw statement that is coded in the try clause will contain an expression that will be caught by the catch clause. Preferably the expression takes the form of an instance of the Error object:

throw new Error("Naughty Naughty! You broke it!!");

However, the expression of the throw statement can be a string or number that describes the error:

throw "User entered value out of range."; throw 1622;

In any event, the catch clause will catch the value of the expression sent from the throw statement.

The exception may be explicitly thrown with the throw statement or automatically handled and thrown by the browser. This is a lead into the next subject (try/catch/finally statement).



JavaScript: try/catch/finally Statement

When an exception occurs outside of a try/catch statement structure, the exception will be reported to the user. When the exception occurs within a try/catch statement, the exception can be captured by the programmer. The user need not be aware or can be informed more gracefully that an error occurred.

From within the try clause, the exception may be generated under control of:

When the browser throws the exception:

When the programmer throws an exception, the throw statement is used. The programmer supplies an expression with the throw statement that can be:

The exceptions being thrown from the try clause will be caught in the catch clause.

The following example contains the following points and assumptions:


try {   hypothetical statements that throw an EvalError exception   hypothetical statements that throw an RangeError exception   hypothetical statements that throw an ReferenceError exception   hypothetical statements that throw an SyntaxError exception   hypothetical statements that throw an TypeError exception   hypothetical statements that throw an URIError exception      // below the programmer explicitly throws an exception   If (num >= 4 && num <= 7){     throw new Error("Invalid options are: 4, 5, 6 and 7");   } } catch ( e ) {   switch (e.name)   case "EvalError":     alert("Evaluation Error " + e.message);     break;   case "RangeError":     alert("Range Error " + e.message);     break;   case "ReferenceError":     alert("Reference Error " + e.message);     break;   case "SyntaxError":     alert("Syntax Error " + e.message);     break;   case "TypeError":     alert("Type Error " + e.message);     break;   case "URIError":     alert("URI Encoding Error " + e.message);     break;   default:     if (e instanceof Error) // this exception was thrown with throw statement       alert(e.name + ": " + e.message);     else       alert("Unknown Exception"); } finally {   finally statements }

BOM: onerror Event Handler



Debugging


Using Alerts

A popular practice to aid in debugging code is to place alerts in sections of code that are problem prone. Placing alerts with descriptive messages in strategic sections of code is a common practice. Once your logic and other problems are cleaned up, it will be necessary to clean up (remove) the alerts.


Using the Java Console

The Java console is a log used to record messages. The programmer can trace the flow of program execution via the log. To view the Java Console feature: in the browser, select "Tools" and then "Java Console". To record a message:

System.out.println("message"); // Java java.lang.System.out.println("message"); // JavaScript

Using the Debugger

Most browsers have a debugger but be aware that the implementations are not consistent. Some methods pertinent to debuggers are:

You should determine whether your browser supports these and other debugging aids.



More Detail Related to the Error Objects


Common to all Error subclasses


The Error Class


• Object Description:
The browser/interpreter can not throw an instance of the base Error object. The Error object is created by the programmer using the throw statement.
• Constructor Syntax:
var instanceName = new Error( message );
• Constructor Example:
var errorException = new Error("Error: 7823");
• Constructor Returns:
The constructor returns a new instance of the Error object. The constructor takes a single argument that will populate the message property. The constructor will use an implementation specific default message when the argument to the constructor is not supplied. A new Error instance can also be created when the constructor is used as a function. var instanceName = Error( message );

The EvalError SubClass


• Object Description:
The browser/interpreter can throw an instance of the EvalError when the function eval() was called illegally.
• Constructor Syntax:
var instanceName = new EvalError( message );
• Constructor Example:
var evalException = new EvalError("illegal use of eval function");
• Constructor Returns:
The constructor returns a new instance of the EvalError object. The constructor takes a single argument that will populate the message property. The constructor will use an implementation specific default message when the argument to the constructor is not supplied. A new EvalError instance can also be created when the constructor is used as a function. var instanceName = EvalError( message );

The RangeError SubClass


• Object Description:
The browser/interpreter can throw an instance of the RangeError when a numeric value is not in its valid range.
• Constructor Syntax:
var instanceName = new RangeError( message );
• Constructor Example:
var rangeException = new RangeError("array length error");
• Constructor Returns:
The constructor returns a new instance of the RangeError object. The constructor takes a single argument that will populate the message property. The constructor will use an implementation specific default message when the argument to the constructor is not supplied. A new RangeError instance can also be created when the constructor is used as a function. var instanceName = RangeError( message );

The ReferenceError SubClass


• Object Description:
The browser/interpreter can throw an instance of the ReferenceError when when you attempt to access a variable that does not exist.
• Constructor Syntax:
var instanceName = new ReferenceError( message );
• Constructor Example:
var refException = new ReferenceError("the variable does not exist");
• Constructor Returns:
The constructor returns a new instance of the ReferenceError object. The constructor takes a single argument that will populate the message property. The constructor will use an implementation specific default message when the argument to the constructor is not supplied. A new ReferenceError instance can also be created when the constructor is used as a function. var instanceName = ReferenceError( message );

The SyntaxError SubClass


• Object Description:
The browser/interpreter can throw an instance of the SyntaxError when certain functions (RegExp(), Function(), eval()) experience syntax errors.
• Constructor Syntax:
var instanceName = new SyntaxError( message );
• Constructor Example:
var syntaxException = new SyntaxError("syntax error found in eval method");
• Constructor Returns:
The constructor returns a new instance of the SyntaxError object. The constructor takes a single argument that will populate the message property. The constructor will use an implementation specific default message when the argument to the constructor is not supplied. A new SyntaxError instance can also be created when the constructor is used as a function. var instanceName = SyntaxError( message );

The TypeError SubClass


• Object Description:
The browser/interpreter can throw an instance of the TypeError when the value is not of the type required for the context. Accessing a property of null or undefined values may cause this error. Also, attempting to access a method that is not defined for the class can cause the error And, the error may occur when a function or method is called with too many arguments specified.
• Constructor Syntax:
var instanceName = new TypeError( message );
• Constructor Example:
var typeException = new TypeError("value is not number type");
• Constructor Returns:
The constructor returns a new instance of the TypeError object. The constructor takes a single argument that will populate the message property. The constructor will use an implementation specific default message when the argument to the constructor is not supplied. A new TypeError instance can also be created when the constructor is used as a function. var instanceName = TypeError( message );

The URIError SubClass


• Object Description:
The browser/interpreter can throw an instance of the URIError when URI decoding functions ( decodeURI() and decodeURIComponent() ) incur decoding problems. The encoding functions ( encodeURI() and encodeURIComponent() ) can do the same.
• Constructor Syntax:
var instanceName = new URIError( message );
• Constructor Example:
var URIException = new URIError("decoding error");
• Constructor Returns:
The constructor returns a new instance of the URIError object. The constructor takes a single argument that will populate the message property. The constructor will use an implementation specific default message when the argument to the constructor is not supplied. A new URIError instance can also be created when the constructor is used as a function. var instanceName = URIError( message );

Top            

Rx4AJAX        About Us | Contact Us | Privacy Policy | 2008 This Site Built By PPThompson