O'Reilly logo

Essential ActionScript 3.0 by Colin Moock

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The finally Block

So far, we've discussed only the try and catch blocks in the try/catch/finally statement. As we've seen, a try block contains code that might throw an exception, and a catch block contains code that executes in response to a thrown exception. The finally block, by comparison, contains code that always executes, whether or not code in the try block throws an exception.

The finally block is placed once (and only once) as the last block in a try/catch/finally statement. For example:

try {
  // substatements
} catch (e:ErrorType1) {
  // Handle ErrorType1 exceptions.
} catch (e:ErrorTypen) {
  // Handle ErrorTypen exceptions.
} finally {
  // This code always executes, no matter how the try block exits.
}

Misplacing the finally block causes a compile-time error.

In the preceding code, the finally block executes in one of these four circumstances:

  • Immediately after the try block completes without errors

  • Immediately after a catch block handles an exception generated in the try block

  • Immediately before an uncaught exception bubbles up

  • Immediately before a return, continue, or break statement transfers control out of the try or catch blocks

The finally block of a try/catch/finally statement typically contains cleanup code that must execute whether or not an exception occurs in the corresponding try block. For example, suppose we're creating a space shooter game, and we define a class, SpaceShip, to represent spaceships in the game. The SpaceShip class has a method, attackEnemy( ), which ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required