Adobe Air Adobe Flash CS4 Flex Flash Builder Flash Catalyst

Contact me at : hello[at]gauravjassal[dot]com

Webdevelopment Blog



Catch Errors in ActionScript 3.0
January 23,2009 at 4:28 pm | Actionscript 3, Flash CS4, Flex 3 | 3 Comments

Errors

One thing you may notice about ActionScript 3 how error prone it is or, rather, how error prone it perceives you to be. You’ll see a lot more errors, not only during compile, but also runtime. ActionScript 3 is much less lenient in letting you get away with mistakes or code conflicts. Whereas ActionScript 1 and 2 may silently fail or ignore many errors, ActionScript 3 will be sure to let you know something went wrong.

Synchronous Errors

Normal errors in code which occur as a code block is being executed are synchronous errors. When the Flash player encounters one of these errors in code, an error, or exception, is thrown. At that point the Flash player will suspend all code in the current block and prevent it from continuing unless the exception is taken care of or caught. To catch exceptions in ActionScript, you use a try..catch..finally statement.

The try..catch..finally statement lets you try a block of code possible of throwing an error and react accordingly if an error occurs. It consists of 2 or more blocks of code: an initial try block, consisting of the code that could throw an error, 1 or more catch blocks that catch errors of different types and run if that type of error is thrown, and an optional finally block which is run after the try and any catches whether or not an error occurs. Its format is as follows:

try {
// potential error causing code
} catch (error:Error) {
// error of type Error occurred
// additional catch blocks may follow
} finally {
// optional to follow try and catch blocks
}

If an exception is thrown within a try block, Flash will look through each catch block until a matching error type is found. When a match is found, that code is run followed by the finally block if it exists. Any additional code following a try..catch..finally statement will be executed as normal even if an error occurs because it was caught by the try..catch..finally statement.

Throw custom errors

Errors are not thrown exclusively by Flash. You also have the ability to throw errors in your own code if you so desire. To throw errors you would use the throw statement. The throw statement throws any value that precedes it (namely an Error object). When thrown, the error will act just like any error and would require a try..catch..finally block to be correctly caught.

// Throwing your own errors in ActionScript
throw new Error(”Error message”);

Throwing your own errors can be a helpful debugging tool, especially as you work with more complicated applications.

Asynchronous Errors

Errors can also occur during asynchronous actions, such as loading external content, and take the form of events. These errors cannot be caught with try..catch..finally statements. Instead you have to create event handlers to handle and “catch” the error events. If you do not have an event listener assigned to an error event and that error occurs, the Flash player will inform you of the unhandled error event.

// creating listeners for error events handles
// asynchronous errors
target.addEventListener(ErrorEvent.TYPE, handler);
function handler(event:ErrorEvent):void {
// handle error
}

Creating Asynchronous Errors

If you want to invoke your own asynchronous errors, all you need to do is dispatch an event using dispatchEvent that is of the type ErrorEvent. When an unhandled ErrorEvent reaches the Flash player when authoring in Flash, the output window will display the error.

// target object is an event dispatcher
// that needs to dispatch an error event
target.dispatchEvent(new ErrorEvent(”type”));

Release and Debug Players

The release of the Flash player is available in two versions, the release and debug. The release player is the standard, public player. This player is what you will have installed for your browser(s) when you download and install Flash player from adobe.com.

The debug player is an alternate player with additional debug information and capabilities embedded within it. This makes the player a little heftier in file size (which is why its not preferred for distribution) but also provides popup dialogs for uncaught exceptions and unhandled asynchronous errors – something the public would rather not see when your Flash movie or application runs into a snag. For developers, however, this player provides useful information when testing your movies.

You can find installers for both the release and debug players in the Players folder within your Flash CS3 (or older) install directory.

One thing to keep in mind is that just because the release player doesn’t visually show an error when an exception is thrown, it doesn’t mean that error line is simply ignored like with previous versions of ActionScript. The code block where that error occurred will be exited and the remaining script ignored.
Example: Loading external text with error handling

To load text content from an external source into the Flash player, you would use the URLLoader class. An instance of URLLoader will load a text file into its data property to be read as a string. Because the process of locating, downloading, and reading an external file into the Flash player takes time, events are used to indicate when the content has been loaded and is available. Not only that, events are used to indicate loading progress and also any errors that occur.

The URLLoader class uses the load method to start the loading process which is also capable of throwing exceptions of many different error types. When using the URLLoader class to load external content, its always best to listen for all asynchronous errors as well as call the load method within a try..catch..finally statement.

// load textfile.txt text into loader instance
var request:URLRequest = new URLRequest(”textfile.txt”);
var loader:URLLoader = new URLLoader();

// listen for complete event (and others if desired)
loader.addEventListener(Event.COMPLETE, loadComplete);
// listen for error events
loader.addEventListener(IOErrorEvent.IO_ERROR, loadIOError);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, loadSecurityError);

// complete event handler
function loadComplete(event:Event):void {
trace(loader.data); // textfile.txt contents
}
// handler for IO error
function loadIOError(event:IOErrorEvent):void {
trace(”IOError: “+event);
}
// handler for security error
function loadSecurityError(event:SecurityErrorEvent):void {
trace(”SecurityError: “+event);
}

// try the load operation and
// catch any thrown exceptions
try {
loader.load(request);
}catch (error:ArgumentError){
trace(”ArgumentError: “+error);
}catch (error:MemoryError){
trace(”MemoryError: “+error);
}catch (error:SecurityError){
trace(”SecurityError: “+error);
}catch (error:TypeError){
trace(”TypeError: “+error);
}catch (error:Error){
trace(”Unknown Error: “+error);
}

In the above example, each error event has its own listener tracing the error if an error occurs during loading. Additionally, each type of error thrown by the load operation is being checked within respective catch blocks. An ending catch with the type Error is used in case there was an error thrown not within the other catches. Then that final block would catch the error no matter what it was. And really, you could just have one catch of the type Error to handle all error events. Similarly one event handler could be used for all error events. In doing this you can still catch and handle all errors but it would involve less code.

// load textfile.txt text into loader instance
var request:URLRequest = new URLRequest(”textfile.txt”);
var loader:URLLoader = new URLLoader();

// listen for complete event (and others if desired)
loader.addEventListener(Event.COMPLETE, loadComplete);
// listen for error events using one handler
loader.addEventListener(IOErrorEvent.IO_ERROR, loadError);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, loadError);

// complete event handler
function loadComplete(event:Event):void {
trace(loader.data); // textfile.txt contents
}
// handler for errors
function loadError(event:ErrorEvent):void {
trace(”Error: “+event);
}

// try the load operation and
// catch any thrown exceptions
try {
loader.load(request);
}catch (error:Error){
trace(”Error: “+error);
}

Here, all errors are still accounted for but less code is involved.

Note that the event parameter of the loadError method is typed as ErrorEvent. Just like all errors thrown by Flash are also of the type Error as well as their own type (their classes extend the Error class), the event errors are also of the type ErrorEvent. By typing the event parameter as ErrorEvent, you can be sure that whatever type of error occurs, it will correctly match with the type of event used in the event handler.

3 Responses to “Catch Errors in ActionScript 3.0”

  1. Simon says:

    What about code libraries that are throwing errors during asynchronous operations. Will a try catch around the objects method call cut it?

  2. Neil says:

    Async’ error handling – just what I was looking for.

    Many thanks for the post.

  3. Alexander says:

    Will it work? Maybe:
    loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, loadError);

Leave a Reply

Recent Blog Entry

This extension notifies you with latest London underground tube updates. You can click on the browser button and check the status of any tube line.By default the extension updates the status in every 5 mins.


Read More

In the second example I am going to use Standard PHP Library (SPL) to notify all attendees about the party location change. SPL has 2 interfaces and a Class for Observer.


Read More

The Observer pattern defines a mechanism by which components can opt-in to receive messages when a target object changes its state. Its works similar to Listening to a Change event for a object or Trigger in a database


Read More

Featured Projects

My Blog

© 2008 Gaurav Jassal