jump to navigation

Try..catch..finally statement in Actionscript 3 September 22, 2010

Posted by Tournas Dimitrios in Actionscript.

In Actionscript , errors can be generated both by the Flash runtime (Built-in errors) and by the program that is executing (custom-errors) . In a program , we can respond to , or handle , any error via the try/catch/finally statement. ActionScript 3 is much less forgiven 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. Errors belong to the following categories :

  • Synchronous Errors
  • Asynchronous Errors

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

f 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”);
//A more practical example 
function divideIt(first:Number, second:Number) :Number {
	if(second === 0) {
		throw new Error("You cannot divide by 0.");
	} else {
		return first / second;

try {
	trace(divideIt(20, 10));
	trace(divideIt(20, 0));
catch (e:Error) {

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 {
}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 {
}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.


1. Vittal - January 5, 2012

How to use the try catch block for http service in action script

tournasdimitrios1 - January 5, 2012

Are you talking about the HttpService component of Flex’s SDK ?
If so , I handle errors like :

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
import mx.rpc.events.ResultEvent;
import mx.rpc.events.FaultEvent;
private function requestText(service:HTTPService):void {
private function resultHandler(event:ResultEvent):void {
apiResult.text = event.result.toString();	
private function resultFailed(event:FaultEvent):void {
apiResult.text = event.fault.toString();
<mx:HTTPService id="apiService"
fault="resultFailed(event)" />
<mx:Button id="apiButton" label="Test API Command"
click="requestText(apiService)" />
<mx:TextArea id="apiResult"  x="10" y="54" width="423" height="206"/>	

2. Liviu - December 15, 2014

is there any difference between using “finally”, and simply adding the code after the try…catch (without finally)?

Tournas Dimitrios - December 15, 2014

Yes there is :
The finally statement encloses statements that will execute whether or not an error occurs in the try block. If there is no error, the statements within the finally block execute after the try block statements complete. If there is an error, the appropriate catch statement executes first, followed by the statements in the finally block. So ….. if an error occurs, any code placed outside the try block will never be run . Hope it clarifies your question . Thanks for commenting on this article🙂
Adobe’s documentation page .

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s