User Guide
986 Chapter 2: ActionScript Language Reference
The following example demonstrates a try..catch statement. The code within the try block is
executed. If an exception is thrown by any code within the
try block, control passes to the catch
block, which shows the error message in a text field using the
Error.toString() method.
In the same directory as Account.as, create a new FLA document and enter the following
ActionScript in Frame 1 of the Timeline:
import Account;
var account:Account = new Account();
try {
var returnVal = account.getAccountInfo();
if (returnVal != 0) {
throw new Error("Error getting account information.");
}
trace("success");
} catch (e) {
this.createTextField("status_txt", this.getNextHighestDepth(), 0, 0, 100,
22);
status_txt.autoSize = true;
status_txt.text = e.toString();
}
The following example shows a try code block with multiple, typed catch code blocks.
Depending on the type of error that occurred, the
try code block throws a different type of
object. In this case,
myRecordSet is an instance of a (hypothetical) class named RecordSet whose
sortRows() method can throw two types of errors, RecordSetException and MalformedRecord.
In the following example, the RecordSetException and MalformedRecord objects are subclasses of
the Error class. Each is defined in its own AS class file. (For more information, see “Creating
Custom Classes with ActionScript 2.0” in Using ActionScript in Flash.)
// In RecordSetException.as:
class RecordSetException extends Error {
var message = "Record set exception occurred.";
}
// In MalformedRecord.as:
class MalformedRecord extends Error {
var message = "Malformed record exception occurred.";
}
Within the RecordSet class’s sortRows() method, one of these previously defined error objects is
thrown, depending on the type of exception that occurred. The following example shows how
this code might look:
class RecordSet {
function sortRows() {
var returnVal:Number = randomNum();
if (returnVal == 1) {
throw new RecordSetException();
} else if (returnVal == 2) {
throw new MalformedRecord();
}
}
function randomNum():Number {
return Math.round(Math.random()*10)%3;