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.

We've seen a number of scenarios in which we've caught (trapped) various errors. But what happens if the interpreter never finds a catch block that can handle the thrown exception? If no eligible catch block is found anywhere in the call stack, then the interpreter:

  • Sends the value of the thrown Error object's message property to the Output panel (or simply sends the thrown expression itself if it wasn't an Error object)

  • Aborts execution of all code currently remaining in the call stack (including frame scripts and callback functions such as a setInterval( ) callback)

Execution of the program then resumes normally. For example, if an uncaught exception occurs on frame 1, layer 1 of a movie, the code on frame 2 executes normally. In fact, code on frame 1, layer 2 will also execute normally. For frame-based code, only the specific frame script that generated the uncaught exception is aborted.

The following code demonstrates a method that throws an error that is never caught:

class ErrorDemo {
  public function doSomething ( ):Void {
    // INTERPRETER: Hmm. No try block here.
    // I'll check who called this method.
    throw new Error("Something went wrong");
  }

  public static function startApp ( ):Void {
    // INTERPRETER: Aha, here's who called doSomething( ). But still
    // no try block here. I'll check who called this method.
    doSomething( );
  }
}

// Meanwhile, elsewhere in the program...
// INTERPRETER: Hmm. Well, I searched all the way to the top, and still
//              no try block. I'll send "Something went wrong" to the Output
//              panel. Maybe the programmer will know what to do.
ErrorDemo.startApp( );

As we've just seen, because exceptions bubble up the call stack, it's not necessary for a method to catch its own exceptions. And it's not even necessary for the caller of a method to catch its exceptions. The exception can legally be caught at any level in the call stack. Any method can delegate exception handling to the code that calls it. That said, it's bad form and harmful to a program to throw an exception and then never catch it. You should always catch exceptions or, having encountered an uncaught exception, revise your code so that the exception isn't thrown in the first place.

Unfortunately, there's no way in ActionScript to tell the compiler to force a program to catch its own exceptions. As we'll learn later, ActionScript does not support Java-style checked exceptions, which are exceptions that must be caught in order for a program to compile. In Java terminology, all exceptions in ActionScript are unchecked.