Tip of the Day – When to use try… catch… finally

A wise Adobean once told me to use try / catch / finally statements sparingly. It didn’t mean much to me at the time since I honestly don’t use them very often. Instead, I opt to check conditions prior to executing “at risk” statements.

So… here’s my advice that when it comes to try / catch statements.

Preventing errors from occurring is far better than generally handling them.

Take a look at this example.

var goodObj:Object = {foo: "bar"};
var badObj:Object = null;
function tryErrors(obj:Object):void {
		trace("doing something else");
	try {
	} catch (e:TypeError) {
		trace("error occurred");
/*** OUTPUT ***************
doing something else
error occurred

Do not use blanket try / catch statements.

You gain nothing by catching an exception that your application can’t deal with at that point.
For example, if you’re trying to convert a string to a number, and you know it might fail, but you have a default value, you should catch the exception, set the default value, and allow execution to continue.

Another example, if you try to call a Web Service and the call fails, and that particular call isn’t critical to your application, you could catch the exception, warn the user that some information is not available, and continue execution.

Only use try / catch when you have to.

I don’t have any specific benchmarks, but I do know that using excessive try/catch statements will degrade performance of your flash application. Probably because Flash Player is single threaded, but an Adobe person would probably have more information on that than I do.

An application I worked on a while ago used a try catch block around every single function… not my fault, it’s code that I inherited… anyways, it’s performance and execution times were horrendous.

Related Posts

Comments Closed