How does a return statement inside a try/catch block work?
function example() {
try {
return true;
}
finally {
return false;
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.)
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
.
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);
}
}
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.
Returning from a finally-block
If the
finally
-block returns a value, this value becomes the return value of the entiretry-catch-finally
statement, regardless of anyreturn
statements in thetry
andcatch
-blocks
Reference: developer.mozilla.org
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;
}
}