Copyright © 2004 O'Reilly Media, Inc. All Rights Reserved.
Essential ActionScript 2.0
By Colin Moock
June 2004
ISBN: 0-596-00652-7
More info... .
Available from booksellers or direct from O'Reilly Media, www.oreilly.com.

Cover image
This content is excerpted from the above-named O'Reilly publication, with permission, by agreement with ActionScript.org.

Chapter 10. Exceptions

Table of Contents

10.1. The Exception-Handling Cycle
10.2. Handling Multiple Types of Exceptions
10.2.1. Determining Exception Type Granularity
10.3. Exception Bubbling
10.3.1. Uncaught Exceptions
10.4. The finally Block
10.5. Nested Exceptions
10.5.1. A Nested Exception Bug
10.6. Control Flow Changes in try/catch/finally
10.7. Limitations of Exception Handling in ActionScript 2.0
10.7.1. No Checked Exceptions
10.7.2. No Built-in Exceptions
10.7.3. Exception Performance Issues
10.8. From Concepts to Code

Throughout this book, we've encountered plenty of compile-time errors—errors reported in the Output panel when a movie is exported. If a compile-time error occurs in an ActionScript 2.0 program, compilation fails and Flash won't generate a .swf file to execute. But not all ActionScript errors occur at compile time. Some errors don't occur until runtime, and they may not cause the program to fail completely. For example, suppose we attempt to load an XML file from disk, but the file is not found. If the movie is running in Test Movie mode, the failed load causes the Output panel to display an error message—but the movie continues to run. The following code demonstrates:

// If the specified file doesn't exist...
var xmlDoc:XML = new XML( );
xmlDoc.load("http://www.somenonexistentsite.com/someNonExistentFile.xml");


// ...the Output panel displays:
Error opening URL
"http://www.somenonexistentsite.com/someNonExistentFile.xml"

In an ideal world, we'd like to be able to recover from nonfatal error conditions such as a file-not-found. We'd like to tell the user there was a problem loading the file and perhaps display the problematic filename.

Unfortunately, in ActionScript there are precious few built-in runtime errors and, what's worse, there's no standard error-handling mechanism for dealing with the errors that do occur at runtime—at least, not for the errors that are generated by ActionScript itself. Most errors in ActionScript occur in the form of custom error codes and return values. For example, a method might return the value -1, false, or null to indicate that some operation failed. This requires us to write different, individualized code for each kind of error generated by ActionScript.

Luckily, the situation is not so bleak for our own code. As of Flash Player 7, we can write code that generates standardized errors via the throw statement. We handle those errors via the try/catch/finally statement. (The throw and try/catch/finally statement syntax and behavior are borrowed from Java and C++.)

Tip

The vast majority of ActionScript 2.0 is backward compatible with Flash Player 6. However, the exception-handling features discussed in this chapter require Flash Player 7 to work. Hence, outside this chapter, code examples in this book do not use exception handling. This allows nearly all examples to run cheerfully in Flash Player 6.

The Exception-Handling Cycle

To learn how to dispatch and respond to errors in our own programs, we'll return to the Box class example from Chapter 4. Recall that in the Box class, we defined a setWidth( ) method to set the width property of a Box instance. The setWidth( ) method checks whether a new width is within legal range before changing the width property of the Box instance. If the new width specified is not valid, no change is made, and the method signals a problem by returning the value false. The relevant Box class code follows. (Note that the Box class code in this example is incomplete; for now we're concentrating only on the portions of the class that deal with setting the width property.)

class Box {
private var width:Number;

public function setWidth (w:Number):Boolean {
if ((isNaN(w) || w == null) || (w <= 0 || w > Number.MAX_VALUE)) {
// Invalid data, so quit.
return false;
}
width = w;
return true;
}
}

When setWidth( ) returns the value false, it does so to indicate an error condition. Code that invokes the setWidth( ) method is expected to check setWidth( )'s return value and respond gracefully if there's a problem (i.e., if setWidth( ) returns false).

Let's now revise the setWidth( ) method so that it generates an exception, a standard form of error supported directly by ActionScript 2.0. Error dispatch and recovery with exceptions works in much the same way as the preceding setWidth( ) method; when a problem occurs, an error is signaled, and some error-recovery code is expected to handle it.

To generate an exception (i.e., signal an error) in our code, we use the throw statement, which takes the following form:

throw expression

where expression is a data value that describes the unusual or problematic situation. Using throw to signal an error is known as "throwing an exception." ActionScript allows any value to act as the expression of a throw statement. For example, the expression value could be the string literal "Something went wrong!" or it could be a numeric error code. However, the best practice is for expression to be an instance of the Error class (or an instance of a subclass of Error).

The Error class, introduced as a built-in class in Flash Player 7, is a standard class for representing error conditions. Instances of the Error class represent an error (a.k.a. an exception) in a program.

Tip

The Error class defines two public properties, name and message , used to describe the error. The Error class also defines a single method, toString( ), which returns the value of message or, if message is not defined, returns the string "Error."