Vexi PlatformVexi Platform
vexi: easy, extensible, flexible

Thursday, April 30, 2009

Tip: never return in a 'finally' block

This one has had me a couple of times. When you return in a finally block, Vexi will not log the exception because the return indicates that the function or trap has concluded successfully.

The symptom is code not being executed fully - a premature stop somewhere. The premature stop to the code path is caused by an exception, e.g. accessing a property on a null object.

var somefunc = function() {
    var nullobj; = "bar"; // error!
    return true;

/** misguided function to return true on success, false otherwise */
var sometest = function() {
    var ret = false;
    try { ret = somefunc(); }
    finally { return ret; }

Of course the above code path does look, as described, misguided. However in more complicated scenarios, especially when working with RPC, it can be easy to forget the intended notion of a finally clause - to clean up necessary resources - and slip in a return. Mostly it will be harmless but on the occasions that the code path embedded in the try clause throws an error, you'll find yourself dumbfounded as to why your code path is not completing and why there is no indication of the problem.

There is a simple rule to follow to avoid this problem (which can take hours to diagnose!) and that is to either A) never 'return' in a 'finally' or B) always preceeded a 'finally' with a 'catch(e) {; }' to make sure the error is logged.


No comments: