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

Why does a return in `finally` override `try`?(为什么`finally`中的返回会覆盖`try`?)

本文介绍了为什么`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.

这篇关于为什么`finally`中的返回会覆盖`try`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:为什么`finally`中的返回会覆盖`try`?

基础教程推荐