try catch mistakes

To cope with errors in code we can do many thing, among many approaches the most powerful is to use “try catch finally” block around the code that might cause trouble (one we know that it throws Errors) but what I have noticed working with different programmers common mistake is to use “try catch” block as a filter of errors.

try
{
   willCauseTrouble();
}
catch(e:*)
{
}

This is just asking for trouble we have no way to cope with that, if you did use the “try catch”, at least use it to report errors:

try
{
   willCauseTrouble();
}
catch(e:*)
{
   trace("error occurred\n"+(e as Error).getStackTrace());
}

next thing is that instead of isolating the code that can cause trouble programmer wraps entire block of code within “try catch” statement.

/**
 * Dummy method to simulate error throwing
 */
function problematicCode():void
{
      throw new Error("Error");
}



try
{
      trace("action 1");
      problematicCode();
      trace("this action will not be executed")
}
catch(e:*)
{
      trace("I have caught an error");
}

above snippet pictures this perfectly, the second trace is not executed, can you see my point, by wrapping entire block of code in the try we are stopping further execution, and it is a show-stopper. You should always try to predict which piece of code might be problematic, and “try catch” only it.

//-----------------
trace("action 1");
try
{
      //isolated problem
      problematicCode();
}
catch(e:*)
{
      trace("I have caught an error");
}
trace("this action WILL BE executed")

And as last word, this is debug utility not perfect hideout:) if your code throws errors, it can still work, but you should fix the cause, always.

happy coding

This entry was posted in actionscript, flash and tagged , , . Bookmark the permalink.