Portrait Dr. Axel Rauschmayer
Dr. Axel Rauschmayer
Homepage | Twitter
Cover of book “Exploring ES6”
Book, exercises, quizzes
(free to read online)
Logo of newsletter “ES.next news”
Newsletter (free)
Cover of book “JavaScript for impatient programmers”
Book (free online)

JavaScript: try-finally

[2013-03-11] dev, javascript, jslang
(Ad, please don’t block)

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.