Error Handling

ActionScript 3.0 supports runtime error handling. That means that if and when an error occurs, the application can respond to the error in an elegant fashion rather than simply failing to work without any notification to the user. ActionScript 3.0 uses two types of runtime errors: synchronous and asynchronous.

Handling Synchronous Errors

Synchronous errors occur immediately when trying to execute a statement. Use try/catch/finally to handle synchronous errors. When you have code that may throw runtime errors, surround it with a try statement:

try {
  // Code that might throw errors
}

You must then include one or more catch blocks following a try. If the code in the try block throws an error, the application attempts to match the error to the catch blocks in the order in which they appear. Every catch block must specify the specific type of error that it handles. The application runs the first catch block that it encounters to see whether it matches the type of error thrown. All error types are either flash.errors.Error types or subclasses of Error. Therefore, you should try to catch more specific error types first and more generic types (e.g., Error) later; for example:

try {
  // Code that might throw errors
}
catch (error:IOError) {
  // Code in case the specific error occurs
}
catch (error:Error) {
  // Code in case a non-specific error occurs
}

In addition, you can add a finally clause that runs regardless of whether the try statement is successful. A finally clause is used to run any code necessary based on any part of the try or catch blocks having run. For example, if you open something in a try block, you might close it in a finally clause.

try {
  // Code that might throw errors
}
catch (error:IOError) {
  // Code in case the specific error occurs
}
catch (error:Error) {
  // Code in case a non-specific error occurs
}
finally {
  // Code to run in any case
}

Most Flash Player and Flex framework classes use asynchronous errors rather than synchronous errors, so the following example may seem impractical, but it does illustrate the syntax for using try/catch. The browse() method for a FileReference object opens a browse dialog box that lets the user select a file from his local filesystem. However, Flash Player can display only one browse dialog box at a time. If you call browse() while a browse dialog box is already open, it throws a flash.errors.IOError type of error. If you don’t handle the error, the user receives a notification in a default error dialog box.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
initialize="initializeHandler(event)">
  <mx:Script>
    <![CDATA[

      import flash.net.FileReference;

      private function initializeHandler(event:Event):void {
        var file:FileReference = new FileReference();
        file.browse();
        file.browse();
      }

    ]]>
  </mx:Script>

</mx:Application>

The following example rewrites the preceding code using error handling:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
initialize="initializeHandler(event)">
  <mx:Script>
    <![CDATA[

      import flash.net.FileReference;

      private function initializeHandler(event:Event):void {
        var file:FileReference = new FileReference();
        try {
          file.browse();
          file.browse();
        }
        catch(error:Error) {
          errors.text += error + "\n";
        }
      }

    ]]>
  </mx:Script>

  <mx:TextArea id="errors" />

</mx:Application>

Handling Asynchronous Errors

Many objects in ActionScript can potentially throw asynchronous errors. Asynchronous errors are those that occur in response to network operations. For example, if a requested file is not found, the network operation fails asynchronously, and an asynchronous error is thrown. All asynchronous errors are in the form of events, and they use the same event model as standard events. For example, if a URLLoader object attempts to load data outside the Flash Player security sandbox, it dispatches a securityError event.

The following example illustrates how to handle error events:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
initialize="initializeHandler(event)">
  <mx:Script>
    <![CDATA[

      private function initializeHandler(event:Event):void {
        var loader:URLLoader = new URLLoader();

         // In order to test this you'll need to specify a URL of a file that
         // exists outside of the security sandbox.
        loader.load(new URLRequest("data.xml"));
        loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR,
securityErrorHandler);
      }

      private function securityErrorHandler(event:SecurityErrorEvent):void {
        errors.text += event + "\n";
      }

    ]]>
  </mx:Script>

  <mx:TextArea id="errors" />

</mx:Application>

Get Programming Flex 3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.