2013-03-11

JavaScript: try-finally

This blog post is a quick reminder of how try-finally works.

Question: what is the output the following code?

    var count = 0;
    function foo() {
        try {
            return count;
        } finally {
            count++;
        }
    }
    console.log(foo());
    console.log(count);
The output is:
    0
    1
Thus:
  • The finally clause is always executed, no matter what happens inside the try clause (return, exception, break, normal exit).
  • However, it is executed after the return statement.

3 comments:

dodo said...

What should happend with :
count = foo();

Does this look right?

1) return count;
2) count ++ //count become 1
3) count = 'what was returned, i.e. 0'

Axel Rauschmayer said...

That looks OK, you’d have to step through it in a debugger.

Šime Vidas said...

In that case the function would return undefined since count is only assigned after the return, so it's still undefined when the return statement executes. Next, the finally block will add 1 to undefined which evaluates to NaN.

Web Analytics