This page looks best with JavaScript enabled

Finally block has the final say

 ·   ·  ☕ 1 min read

Finally overrides any return statement from the try/catch.

We write try/catch/finally for error handling in Javascript -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function tryTryTry() {
  try {
    return 4;
  } catch (e) {
    console.log(e);
  } finally {
    return 42;
  }
}
console.log(tryTryTry());
//42

The function returns 42 and not 4.

Why? Because finally always gets executed - both for the normal execution flow and errors. In the above code block -

  1. try returns 4
  2. control flow jumps to finally block
  3. finally returns 42
  4. caller gets 42
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things