Chapter 10. Exceptions

 <  Day Day Up  >  

Throughout this book, we've encountered plenty of compile-time errors ”errors reported in the Output panel when a movie is exported. If a compile-time error occurs in an ActionScript 2.0 program, compilation fails and Flash won't generate a .swf file to execute. But not all ActionScript errors occur at compile time. Some errors don't occur until runtime, and they may not cause the program to fail completely. For example, suppose we attempt to load an XML file from disk, but the file is not found. If the movie is running in Test Movie mode, the failed load causes the Output panel to display an error message ”but the movie continues to run. The following code demonstrates :

 // If the specified file doesn't exist... var xmlDoc:XML = new XML( ); xmlDoc.load("http://www.somenonexistentsite.com/someNonExistentFile.xml");   // ...the Output panel displays: Error opening URL "http://www.somenonexistentsite.com/someNonExistentFile.xml" 

In an ideal world, we'd like to be able to recover from nonfatal error conditions such as a file-not-found. We'd like to tell the user there was a problem loading the file and perhaps display the problematic filename.

Unfortunately, in ActionScript there are precious few built-in runtime errors and, what's worse , there's no standard error-handling mechanism for dealing with the errors that do occur at runtime ”at least, not for the errors that are generated by ActionScript itself. Most errors in ActionScript occur in the form of custom error codes and return values. For example, a method might return the value -1, false , or null to indicate that some operation failed. This requires us to write different, individualized code for each kind of error generated by ActionScript.

Luckily, the situation is not so bleak for our own code. As of Flash Player 7, we can write code that generates standardized errors via the throw statement. We handle those errors via the try/catch/finally statement. (The throw and try/catch/finally statement syntax and behavior are borrowed from Java and C++.)

The vast majority of ActionScript 2.0 is backward compatible with Flash Player 6. However, the exception-handling features discussed in this chapter require Flash Player 7 to work. Hence, outside this chapter, code examples in this book do not use exception handling. This allows nearly all examples to run cheerfully in Flash Player 6.


 <  Day Day Up  >  


Essential ActionScript 2.0
Essential ActionScript 2.0
ISBN: 0596006527
EAN: 2147483647
Year: 2004
Pages: 177
Authors: Colin Moock

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net