为什么“最终"的回报会覆盖“尝试"? [英] Why does a return in `finally` override `try`?

查看:105
本文介绍了为什么“最终"的回报会覆盖“尝试"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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!

推荐答案

最后总是执行.这就是它的用途,这意味着您的情况将使用返回值.

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

您将要更改代码,因此更像这样:

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

function example() { 
    var returnState = false; // initialisation 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.

这篇关于为什么“最终"的回报会覆盖“尝试"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆