and finally….

The try-catch block is possibly one of the least used elements of AS2. Adobe’s page on the try catch block on livedocs is bare bones and pretty much mentions what it does and little else. For the most part, most flash developers are unfamiliar with the concept of error bubbling and you can pretty much get by without it. For example, if you are reading an xml file, and know that it may not exist, you can construct the code like:


var x:XML = new XML();
x.onLoad = function(success:Boolean){
if(success){
// success
}
else{
this.manager.xmlError();
}
}

Here, the manager.xmlError() function deals with the error situation. However in the try catch block way your code would look like:

var x:XML = new XML();
x.onLoad = function(success:Boolean){
if(success){
// success
}
else{
throw new Error("xml load failed")
}
}

By using the throw keyword, you are declaring that that particular class is aware of a failure situation but its upto some other class which is below the class object on the invocation stack to deal with it (Java also has a 'throws' keyword that is used againt the method name to reinforce the fact that the function will throw an error).

So in AS2 land, while errors were 'nice-to-haves', they were by no means mandatory. This situation has since changed in AS3 and flash developers must now be really aware of this programming paradigm. In AS3, the player itself generates errors in certain situations and it is upto your code to deal with these runtime errors.

If try-catch blocks have been the neglected children of AS2, the finally keyword has been the forgotten one. Most of the code that deals with catching errors pretty uses try and catch but hardly ever finally. Code in 'finally' blocks is guaranteed to execute regardless of what happens in the try-catch block. While explaining the concept of finally, one of my collegues asked me the purpose of finally. For example if you have


try{
}
catch(e){

}
finally{
/// statements here
}

how is that different from
try{

}
catch(e){

}
/// statements here


I did not have any immediate answer for that question besides the better-readability of the code. Reading up on the Java implementation and talking to Java developers (most of whom end up not using it too 😉 ), brought out the most important aspect of the finally statement. The part that I hadnt realized was that the finally block is executed even if your try block succeeds and does a return.

In the meanwhile make sure you are upto speed on compiler errors, warnings and runtime errors in Flash.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s