为什么`finally`中的返回会覆盖`try`?

try/catch 块中的 return 语句如何工作?

How does a return statement inside a try/catch block work?

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

我希望这个函数的输出是 true,但实际上它是 false

I'm expecting the output of this function to be true, but instead it is false!

推荐答案

最后 always 执行.这就是它的用途,这意味着它的返回值会在您的情况下使用.

Finally always executes. That's what it's for, which means its return value gets used in your case.

您需要更改您的代码,使其更像这样:

You'll want to change your code so it's more like this:

function example() { 
    var returnState = false; // initialization value is really up to the design
    try { 
        returnState = true; 
    } 
    catch {
        returnState = false;
    }
    finally { 
        return returnState; 
    } 
} 

一般来说,你永远不想在一个函数中有多个 return 语句,这样的事情就是原因.

Generally speaking you never want to have more than one return statement in a function, things like this are why.

相关文章