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

后端 未结 10 1997
栀梦
栀梦 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

    When you use finally, any code within that block fires before the method exits. Because you're using a return in the finally block, it calls return false and overrides the previous return true in the try block.

    (Terminology might not be quite right.)

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-12 15:51

    What about this?

    doubleReturn();
    
    function doubleReturn() {
      let sex = 'boy';
    
      try {
        return sex;
    
        console.log('this never gets called...');
      } catch (e) {} finally {
        sex = 'girl'; 
    
        alert(sex);
      }
    }
    
    0 讨论(0)
  • 2020-12-12 15:55

    Finally is supposed to ALWAYS run at the end of a try catch block so that (by specification) is why you are getting false returned. Keep in mind that it is entirely possible that different browsers have different implementations.

    0 讨论(0)
  • 2020-12-12 15:56

    Returning from a finally-block

    If the finally-block returns a value, this value becomes the return value of the entire try-catch-finally statement, regardless of any return statements in the try and catch-blocks

    Reference: developer.mozilla.org

    0 讨论(0)
  • 2020-12-12 16:03

    why you are getting false is you returned in a finally block. finally block should execute always. so your return true changes to return false

    function example() {
        try {
            return true;
        }
        catch {
            return false;
        }
    }
    
    0 讨论(0)
提交回复
热议问题