Using try..catch and try..catch..finally statements

Using try..catch..finally blocks lets you add error handling to your Flash applications. The try..catch..finally keywords let you enclose a block of code where an error can occur and respond to that error. If any code within the try code block throws an error (using the throw statement), control passes to the catch block, if one exists. Then control passes to the finally code block, if one exists. The optional finally block always executes, regardless of whether an error was thrown.

If code within the try block doesn't throw an error (that is, the try block completes normally), the code in the finally block still executes.

NOTE

The finally block executes even if the try block exits using a return statement

You write try..catch and try..catch..finally statements using the following format:

// try-catch
try {
  // statements
} catch (myError) {
  // statements
}

// try-catch-finally
try {
  // statements
} catch (myError) {
  // statements
} finally {
  // statements
}

Any time your code throws an error, you can write custom handlers to handle the error gracefully and take appropriate actions. You might need to try loading external data from a web service or text file or to display an error message to the end user. You can even use the catch block to try to connect to a web service that alerts an administrator that a particular error occurred, so he or she can make sure the application works properly.

To use the try..catch..finally block for data validation before dividing some numbers:

  1. Select File > New and then select Flash Document.
  2. Select Frame 1 of the Timeline, and then type the following ActionScript in the Actions panel:
    var n1:Number = 7;
    var n2:Number = 0;
    try {
        if (n2 == 0) {
            throw new Error("Unable to divide by zero");
        }
        trace(n1/n2);
    } catch (err:Error) {
        trace("ERROR! " + err.toString());
    } finally {
        delete n1;
        delete n2;
    }
    
  3. Select Control > Test Movie to test the document.
  4. The Output panel displays Unable to divide by zero.
  5. Return to the authoring environment and change the following line of code:
    var n2:Number = 0;
    

    to

    var n2:Number = 2;
    
  6. Select Control > Enter to test the document again.

    If the value of n2 equals zero, an error is thrown and is caught by the catch block, which displays a message in the Output panel. If the value of y is not equal to zero, the Output panel displays the result of n1 divided by n2. The finally block executes regardless of whether an error occurs and deletes the values of the n1 and n2 variables from the Flash document.

You aren't limited to throwing new instances of the Error class when an error occurs. You could also extend the Error class to create your own custom errors, as demonstrated in the following example.

To create a custom error:

  1. Select File > New and create a new ActionScript file.
  2. Select File > Save As and name the file DivideByZeroException.as.
  3. Type the following ActionScript into the Script pane:
    // In DivideByZeroException.as:
    class DivideByZeroException extends Error {
       var message:String = "Divide By Zero error";
    }
    
  4. Save the ActionScript file.
  5. Create a new Flash document named exception_test.fla in the same directory as the ActionScript file, and then save the file.
  6. Type the following ActionScript into the Actions panel in Frame 1 of the main Timeline:
    var n1:Number = 7;
    var n2:Number = 0;
    try {
        if (n2 == 0) {
            throw new DivideByZeroException();
        } else if (n2 < 0) {
            throw new Error("n2 cannot be less than zero");
        } else {
            trace(n1/n2);
        }
    } catch (err:DivideByZeroException) {
        trace(err.toString());
    } catch (err:Error) {
        trace("An unknown error occurred; " + err.toString());
    }
    
  7. Save the Flash document and select Control > Test Movie to test the file in the test environment.

    Because the value of n2 equals 0, Flash throws your custom DivideByZeroException error class and displays Divide By Zero error in the Output panel. If you change the value of n2 in line two from 0 to -1, and retest the Flash document, you would see An unknown error occurred; n2 cannot be less than zero in the Output panel. Setting the value of n2 to any number greater than 0 causes the result of the division to appear in the Output panel. For more information on creating custom classes, see Classes.