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

后端 未结 10 2003
栀梦
栀梦 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 15:50

    The finally block rewrites try block return (figuratively speaking).

    Just wanted to point out, that if you return something from finally, then it will be returned from the function. But if in finally there is no 'return' word - it will be returned the value from try block;

    function example() {
        try {
            return true;
        }
        finally {
           console.log('finally')
        }
    }
    console.log(example());
    // -> finally
    // -> true
    

    So -finally- return rewrites the return of -try- return.

提交回复
热议问题