Why does a return in `finally` override `try`?

后端 未结 10 2027
栀梦
栀梦 2020-12-12 15:22

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

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


        
10条回答
  •  长情又很酷
    2020-12-12 16:09

    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; 
        } 
    } 
    

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

提交回复
热议问题