Copyright © 2004 O'Reilly Media, Inc. All Rights Reserved.
Essential ActionScript 2.0
By Colin Moock
June 2004
ISBN: 0-596-00652-7
More info... .
Available from booksellers or direct from O'Reilly Media, www.oreilly.com.

Cover image
This content is excerpted from the above-named O'Reilly publication, with permission, by agreement with ActionScript.org.

Example 10-2. Using return in try, after throw

function changeFlow ( ):Void {
  try {
    throw new Error("Test error.");
    return;
  } catch (e:Error) {
    trace("Caught: " + e);
  } finally {
    trace("Finally executed.");
  }
  trace("Last line of method.");
}


// Output when changeFlow( ) is invoked:
Caught: Test error.
Finally executed.
Last line of method.

Example 10-3 shows a return statement in a catch block. In this case, the return statement executes when the work of error handling is done, and the code after the try/catch/finally statement never executes. However, as usual, before the method returns, the finally block is executed. Unlike Examples 10-1 and Example 10-2, this code is typical of a real-world scenario in which a method is aborted due to the occurrence of an error.

Example 10-3. Using return in catch

function changeFlow ( ):Void {
  try {
    throw new Error("Test error.");
  } catch (e:Error) {
    trace("Caught: " + e);
    return;
  } finally {
    trace("Finally executed.");
  }
  trace("Last line of method.");
}


// Output when changeFlow( ) is invoked:
Caught: Test error.
Finally executed.

Last, Example 10-4 shows a return statement in a finally block. In this case, the return statement executes when the finally block executes (as we learned earlier, a finally block executes when its corresponding try block completes in one of the following ways: without errors, with an error that was caught, with an error that was not caught, or due to a return, break, or continue statement). Notice that the return statement in Example 10-4 prevents any code in the method beyond the try/catch/finally statement from executing. You might use a similar technique to quit out of a method after invoking a block of code, whether or not that code throws an exception. In such a case, you'd typically surround the entire try/catch/finally block in a conditional statement (otherwise the remainder of the method would never execute!).

Example 10-4. Using return in finally

function changeFlow ( ):Void {
  try {
    throw new Error("Test error.");
  } catch (e:Error) {
    trace("Caught: " + e);
  } finally {
    trace("Finally executed.");
    return;
  }
  trace("Last line of method.");  // Not executed.
}


// Output when changeFlow( ) is invoked:
Caught: Test error.
Finally executed.

If a return statement occurs in a finally block after a return has already been issued in the corresponding try block, then the return in the finally block replaces the return already in progress.