Friday, July 22, 2011

Try Catch Error Smartly

I assume you are not strange to "try, catch, error" in javascript (or in other programming langauge).  As you know, this "try, catch" thing is trying to maintain the quality of the code, to clean things up ... etc.  But it also could be the source of your error ( a programming bug by itself as well ).

Let's take a look at the following example  ( it's just arbitrary example ):

for(;;) {
  try {
     alert(parseInputNumber() + 1);
     break;
  } catch (e) {
     alert("something wrong in your code");
  }
}

Do you see a problem here, or potentially a problem?  What if the "parseInputNumber()"  throws the error?  And yes, if "parseInputNumber()" throws error, it will be catch and then go to the loop again, and it could never reach the "break" statement.  The programmer assumed the "parseInputNumber()" is always passed, and hope that it will break out of the for loop afterwards.

One way to solve this issue is to introduce an error type in the "parseInputNumber()" function, and if inside that function has error, it will throws that error type.  And we will need to rewrite our try catch block like the following:-


for(;;) {
  try {
     alert(parseInputNumber() + 1);
     break;
  } catch (e) {
     if(e != myCustomInvalidType) throw e;
     alert("something wrong in your code");
  }
}

In this way, you've just created an unhandled exceptions (if myCustomInvalidType is thrown), and it will make all the way throw to the bottom of the stack if you do not catch it. 

The above is just a simple and arbitrary example, but it states that your try catch block could be your problem if you use it carelessly.

Below are some extra notes (about try catch thing) for people who are new in javascript:-
- In javascript, you can clean up the resources (similar to how java did it) using finally.

try {
  // do some stuff
} finally {
  // last chance to clean the stuff
}

- You can throw custom error type by doing so:-

var myCustomErrorType = new Error("You have a custom error whatever");
throw myCustomErrorType;

Hopefully it covers the basic of the try catch thing in javascript, let me know if I'm missing some other important information :)

No comments:

Post a Comment