Exception Handling

 < Day Day Up > 

An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. Many kinds of errors can cause exceptionsproblems ranging from serious hardware errors, such as a hard disk crash, to simple programming errors, such as trying to access an out-of-bounds Array element. The exception handling and debugging in Macromedia Flash MX 2004 has been greatly improved from previous versions of Flash. With the robust exception handling now available, ActionScript joins the ranks of other languages such as C#, Java, and even JavaScript in its handling of errors that occur at execution.

Robust error handling allows the creation and debugging of complicated applications, such as the call center application created in the previous chapter. In previous versions of ActionScript, there were many silent errors , where the Flash Player would fail at execution but no message would be generated to the developer.

In this part of the chapter, you will learn how to avoid this by establishing good coding practices by separating error handling from regular code. ActionScript 2.0 provides three new operators that take care of all exception handling, and only exception handling is done with these operators. They are try , catch , and finally . You still have to manually build in all exception handling using the try / catch / finally keywords; if not, the player will fail silently.

W arning

Note that exception handling will not work in the Flash 6 Player; it is only supported in the Flash 7 Player. If you publish for the 6 Player, all try/catch/throw/finally statements will be commented out and functionality will be lost.


Exception handling is available in either ActionScript 1 or 2, but you must target the Flash 7 Player.

Errors usually prevent the program from continuing while with exceptions, the program can continue although it may be crippled. Exception handling allows us to write our own code to replace the default behavior of the Flash Player. In most cases, of course, the player does nothing when encountering an exception.

Exception handling also allows the developer to control the error information that end users end up seeing; we can easily write custom error messages that will handle situations specific to the call center application. If we write our exception handlers effectively, it will allow the Flash Player to easily recover from exceptions (for example, not loading data properly) and move on to the next task while interrupting the flow of the application as little as possible. We could also easily send the diagnostic information to a database so it can be stored and viewed later. The try , throw , and catch keywords allow us to separate all of our runtime exception handling from our regular code.

Using the Try, Throw, Catch , and Finally Keywords

Generally, as we have seen, when the Flash Player encounters an exception nothing at all is displayed to the end user in the Player. For example, consider the following code:

 var myXML: XML = new XML(); myXml.load ("http://localhost/xml/magazines.xml"); myXMl.onLoad = function () { //code to process XML } 

This code will work perfectly if the server is running and the XML file is located in the appropriate directory. However, if the server happens to be down nothing will be displayed to the user in the Flash Player. The developer will see an Unable to load URL message in the development environment. This can make debugging a nightmarethe user may not have Internet access, the server could be down, the directory path could be wrong, or there could be all kinds of issues affecting this at runtime. Without runtime exception handling, neither the end user or the developer would know anything went wrong.

Of course, the application would not function properly, but it would be ideal if the developer could write some code that would allow the application to continue its flow, despite the error. For example, we would want to tell the user that an error has occurred possibly by populating an alert or a text box with a message. It might be possible to load the data from a shared Object instead of the server; we may want to tell the user to check his or her Internet connection. All of this is easily achieved using the new exception handling built into Flash MX 2004. The general structure of exception handling is as follows :

 try { //this is the code that performs an action that could fail //this code MUST have conditional logic that tests for a failure //this code MUST have a throw statement that returns an error } catch (error) { //this code is only called if an error is thrown. Within this code we  could load data from a shared Object, we could display a message to  the user, we could save information to a database. } finally { //this code is called every time whether there is an error or not. It is called after all other code has been executed. For example, onLoad of an XML Object will be called before this code is executed. It is useful for cleaning up. } 

Of course, it would be possible to handle the error using regular conditional logic but ActionScript 2.0 allows a more robust and flexible way through exception handling. We surround the code with try , catch , and/or finally statements. In this situation, the XML, for whatever reason, may not load properly. With the try keyword and conditional logic, ActionScript will display an error using the throw keyword:

 try { myXml.load ("http://localhost/xml/magazines.xml"); if (//check to see if XML loaded) { throw "XML was not loaded"; } } 

The throw statement will return any type of Object in Flash from a Boolean to a custom class, as shown here:

 throw false; throw new XmlErrorClass(); 

The best way to display an error is to use the new Error class or use a custom class that extends the error class. The class in Macromedia Flash MX 2004 allows error messages to be displayed. It contains a toString method as well as two properties, message and name . For example, in the following code:

 var myError :Error = new Error("XML could not be loaded""); 

the message property of the error Object would be "XML cannot be loaded" and the name property would be Error , which is the default value. See Table 17.1.

Table 17.1. Properties and Methods of the Error Class






Converts an error message into a string. By default, returns the string Error .



Contains the error message, which the developer can specify.



A string that contains the name of the error Object.

The following code would try to load in the XML file and throw an error if it was unable to do so:

 var myXml: XML = new XML(); try { myXml.load ("http://localhost/xml/magazines.xml"); //attempt to load the XML if (//code to check if XML loaded)         {             throw new Error ("Could not load XML");         } } 

A best practice is to create custom classes for each type of error that could be thrown. For example, in the previous case, it may be useful to create a custom class that indicates whether or not XML has been successfully loaded, in order to better manage types of exceptions.

 class XmlLoadError extends Error {     var message :String;     function XmlLoadError ()     {         this.message = "XML could not be loaded";     }     public function getError()     {         return this.message;     } } 

The exception handling would now look like this:

 var myXml: XML = new XML(); try { myXml.load ("http://localhost/xml/magazines.xml"); //attempt to load the XML if (//code to check if XML loaded) //XML could not be loaded         {             var magazineLoadError :XmlLoadError = new XmlLoadError();             throw XmlLoadError.getError();         } } 

Our exception handling is not complete yet. In fact, if you compile the previously listed code, Flash will generate an error. A try statement must be followed by either a finally statement or a catch statement. Once the throw keyword has been executed (for example, an exception has been caught), control is automatically passed to the catch statement. It is important to note that the rest of the code in the try block will not be executed so it's important to surround only related code with try statements. Again, the catch statement is only called if an exception is thrown. Each try block can only have one catch block.


You can have as many try blocks as you like nested within each other, but each try block can only have one catch block.

The error message from the appropriate try block is passed to the catch statement as a parameter. The catch statement is where we would notify the user that an error occurred, possibly by populating a text box or alert component. In the catch statement, we may load in XML from a shared Object, or ask the user to check his or her Internet connection.

We can also define a finally handler. The finally handler will always execute whether or not an error is actually thrown, so that limits its use for actually catching errors or performing alternative actions. However, the finally handler can be very useful for performing cleanup actions such as deleting Objects because it is executed after the catch and try statements.

In the following step sequence, we use the try / catch / finally statements for simple form validation.

  1. Create a simple form with two text area components : a push button and a label component. Use the component inspector so the label of the push button is submit and the text of the label component is user . Arrange the components so they look like Figure 17.9.

    Figure 17.9. UI of a simple Flash form.


  2. Assign the top text area component an instance name of user_txt . Assign the bottom text area component an instance name of message . Assign the push button an instance name of submit _pb .

  3. Add a click listener to the push button by adding the following code:

     var clickObj :Object = new Object; clickObj.click = function (){     } submit_pb.addEventListener ("click", clickObj); 
  4. Within the click method of the clickObj Object, add the following try / catch statement to test for form validation. Ensure that the code appears as shown here:

     var clickObj :Object = new Object; clickObj.click = function (){ try {      if (user_txt.length < 1 ) {          throw new Error ("User field must be populated"); } } catch (e) {       message.text = e; } } submit_pb.addEventListener ("click", clickObj); 
  5. Test the movie. Note that if you leave the user field blank, the error message will appear in the message text area component. If the user field is populated, no error occurs.

  6. Within the click method of the clickObj Object, add a finally statement that will trace the contents of the message field. This will display the error message; because it displays the error message, it means that the finally statement has been executed after the catch statement. This makes finally extremely useful for performing actions that must be done each time whether or not an error occurs. Be sure the click method appears:

     var clickObj :Object = new Object; clickObj.click = function (){ try { if (user_txt.length < 1 ) { throw new Error ("User field must be populated"); } } catch (e) { message.text = e; } finally {     trace (message.text); } } submit_pb.addEventListener ("click", clickObj); 

Using Error Handling in Functions

We could surround a group of functions with a try statement and if any one of those functions generated an exception, we could handle it in the catch statement. In the example shown next, if the user left any of the fields blank, ActionScript would display the appropriate error message to the user:

 function checkUser() {    if (user.length <1 ) {     throw new Error ("User field must be populated"); } } function checkAddress () {    if (address.length <1 ) {     throw new Error ("Address field must be populated"); } } function checkState () {    if (state.length < 1) {     throw new Error ("State field must be populated"); } } try { checkUser(); checkAddress(); checkState(); } catch (e) { message.text = e; } 

This is an example of bubbling up . If a function does not handle an exception that is thrown by using a catch statement, the function stops executing and the same check is performed on the next outer function. The function calls are unwound until a catch handler is found. If no catch handler is ever found, then the entire script stops executing. In this case, a catch handler is found on the main timeline.

 < Day Day Up > 

Object-Oriented Programming with ActionScript 2.0
Object-Oriented Programming with ActionScript 2.0
ISBN: 0735713804
EAN: 2147483647
Year: 2004
Pages: 162

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