2

I've run into some problems in my code, and so I have narrowed it down to this simple use-case:

function func() {
    try {
        return true;
    }
    finally {
        return false;
    }
}

console.log(func());

To my extreme surprise, the printout of the code above is false.

Now, I could easily solve it with:

function func() {
    try {
        return true;
    }
    catch (error) {
    }
    return false;
}

In fact, that was my original code, but then I figured it would look nicer with finally.

I have read this MDN post, which gives three forms for the try statement:

  1. try...catch
  2. try...finally
  3. try...catch...finally

The 2nd form looks perfect for my use-case.

I am finding it extremely bewildering that the return statement in the finally part "overrides" the return statement in the try part.

In fact, I am not even sure how this behavior is achieved via "compilation" (double quoting, because I know that this term doesn't really apply for Javascript).

Common sense tells me that the code inside the finally part is placed at the end of the try part and (optionally) at the end of the catch part.

In fact, I'm pretty sure that this is the case in compiled languages like C++ and Java, though for the sake of my question, it is not really important whether or not this is how finally is implemented behind the scene.

My question - how is it possible for the return statement of the try part to be so brutally ignored here? What have I missed about finally?

halfer
  • 19,824
  • 17
  • 99
  • 186
goodvibration
  • 5,980
  • 4
  • 28
  • 61
  • *"What have I missed about `finally`?"* Finally is **guaranteed** to be executed, even after a `return` or an `Error`. How would **you** solve this problem in your snippet? Returning twice in the same function call; because again, the second `return` is guaranteed to be executed even after the first `return`. – Thomas Aug 09 '19 at 12:27

0 Answers0