what happen to return statement in catch block

I understand Finally always execute regardless of result of try catch
but what happen to return statement in catch .

Return statement in catch will be executed only if the catch block is reached, i.e. if there is an error thrown.

For example

function example() { 
    try { 
        throw new Error()
        return 1;
    } 
    catch(e) {
        return 2;
    }
    finally { 
    } 
} 

example() will return 2 since an error was thrown before return 1.

But if there is a finally block and this finally block has a return statement then this return will override catch return statement.

For example

function example() { 
    try { 
        throw new Error()
        return 1;
    } 
    catch(e) {
        return 2;
    }
    finally { 
        return 3;
    } 
} 

Now example() will return 3.

In your example, there is a return statement after the finally block. That statement will never get executed.

Try

function example() { 
    try { 
        throw new Error()
        return 1;
    } 
    catch(e) {
        return 2;
    }
    finally { 
        return 3;
    } 
   console.log(5)
   return 4;
} 

It only outputs 3. 5 is never printed since after finally block value is returned.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)