The finally block always executes last and the return statement returns control back to where the function call was made from. When used together from inside of try/finally block, the function appears to return twice instead of once, when used inside an if-else block, the finally block's return value takes effect. Is the same method call returning twice?
function print(value) {
console.log(value);
return value;
}
function testWrapped() {
try {
return print(true);
} finally {
return print(false);
}
}
function test() {
try {
return true;
} finally {
return false;
}
}
console.log("Result with wrapped value");
testWrapped();
console.log("Result when used inside an if statement:");
if (test()) {
console.log("true");
} else {
console.log("false");
}
the above code produces the following output:
Result with wrapped value
true
false
Result when used inside an if statement:
false
This is because you are using finally and not catch
Finally will execute after either try or catch.
In the conditional block, it will return the last evaluated item, false, and execute your else block.
see: https://www.w3schools.com/jsref/jsref_try_catch.asp
The try statement allows you to define a block of code to be tested for errors while it is being executed.
The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
The finally statement lets you execute code, after try and catch, regardless of the result.
Both are evaluated, but only the second one is actually returned.
Since the evaluation of print() has the side-effect of outputting to the console, you can see the evaluation. But if you were to console.log(testWrapped()) you would see the returned value after the two evaluated values.
Your code is equivalent to:
try {
result1 = print(true);
return result1;
}
finally {
result2 = print(false);
return result2;
}
Hopefully that makes it clearer what's going on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With