User Guide

220 Chapter 5: ActionScript Core Language Elements
If an error is thrown within a function, and the function does not include a catch handler, then
the ActionScript interpreter exits that function, as well as any caller functions, until a
catch block
is found. During this process,
finally handlers are called at all levels.
Example
The following example shows how to create a try..finally statement. Because code in the
finally block is guaranteed to execute, it is typically used to perform any necessary clean-up
after a
try block executes. In the following example, setInterval() calls a function every 1000
millisecond (1 second). If an error occurs, an error is thrown and is caught by the
catch block.
The finally block is always executed whether or not an error occurs. Because
setInterval() is
used,
clearInterval() must be placed in the finally block to ensure that the interval is
cleared from memory.
myFunction = function () {
trace("this is myFunction");
};
try {
myInterval = setInterval(this, "myFunction", 1000);
throw new Error("my error");
} catch (myError:Error) {
trace("error caught: "+myError);
} finally {
clearInterval(myInterval);
trace("error is cleared");
}
In the following example, the finally block is used to delete an ActionScript object, regardless of
whether an error occurred. Create a new AS file called Account.as.
class Account {
var balance:Number = 1000;
function getAccountInfo():Number {
return (Math.round(Math.random()*10)%2);
}
}
In the same directory as Account.as, create a new AS or FLA document and enter the following
ActionScript:
import Account;
var account:Account = new Account();
try {
var returnVal = account.getAccountInfo();
if (returnVal != 0) {
throw new Error("Error getting account information.");
}
} finally {
if (account != null) {
delete account;
}
}