Monday, May 17, 2010

Understanding Try/Catch in ActionScript

Understanding Try/Catch in ActionScript

By: Joey Lott

Page 5 of 5

Set for printing

Previous

Using finally

There's yet another block you can optionally include with try/catch. A finally block can appear after the try and catch blocks, and it can contain code that is run regardless of what happens within the try and/or catch blocks. For example:

try {
trace("try");
}
catch (errObject:Error) {
trace("catch");
}
finally {
trace("finally");
}

The preceding code will output:

try
finally

Since no error is thrown, the catch block doesn't run. However, the finally block does run.

Similarly, the finally block will run even when an error is thrown:

try {
throw new Error();
trace("try");
}
catch (errObject:Error) {
trace("catch");
}
finally {
trace("finally");
}

The preceding code outputs:

catch
finally

The trace("try"); is not run because it occurs after the error is thrown. But the finally block still runs.

The uses of finally are a little more obscure than the uses of try and catch. Obviously the following code accomplishes the same thing as the preceding, but without a finally block:

try {
throw new Error();
trace("try");
}
catch (errObject:Error) {
trace("catch");
}
trace("finally");

Using the finally block does tend to make the code somewhat more readable. However, there are some functional differences between using a finally block and not using a finally block that can be seen in certain contexts. For example, consider the following:

function someFunction():Void {
try {
throw new Error();
trace("try");
}
catch (errObject:Error) {
trace("catch");
return;
}
finally {
trace("finally");
}
}

If you call someFunction(), then you will see that the following is displayed in the Output panel:

catch
finally

That is because the finally block runs regardless of what happens in the try or catch blocks. So even though the catch block has a return statement that exits the function, the finally block runs. Compare that with the following:

function someFunction():Void {
try {
throw new Error();
trace("try");
}
catch (errObject:Error) {
trace("catch");
return;
}
trace("finally");
}

The preceding code will simply display:

catch

The finally is not displayed because the function is exited by the return statement in the catch block.

Conclusion

In this article you've had a chance to learn about the basics of implementing try/catch in your ActionScript code. Using try/catch is a good practice to start using, particularly when building libraries of classes. When appropriate, your methods should throw errors. Make sure to document the errors that methods can throw so that they can be properly handled.

No comments:

Post a Comment