In relation to: Java try-finally return design question
This doesn't quite answer my question also may not be relevant since it's java and not javascript: What is the order of execution in try,catch and finally
I understand that putting a return in a finally
block will take precedence over a return in a catch
block, however how does the sequence events work with the following code?
function confusion(){
var test = "a";
try{
return test;
}
finally{
test = "b";
}
}
console.log("Result", confusion()); //"a"
My general understanding of returning of anything is that control usually returns to the context of where the method is being called, so the fact that execution continues is kind've confusing to me.
In this scenario I thought it might play out something like:
-Function set to return test
-> finally
changes value of test
-> test
is returned with updated value.
But instead it seems like some sort've state is held for the try
block and finally
misses the timing?
When you return
out of a try
or catch
block with an associated finally
block, execution enters the finally
block because that's the purpose of it: To handle common completion actions for the try
/catch
.
In your code, what happens as of the return
is:
The value of test
is read from the variable and set aside for use later.
Control passes to finally
.
Code in finally
changes the value of the variable test
(which has no effect on the value that was set aside in #1).
When the end of the finally
block is encountered, the function returns, using the value set aside in #1 as its return value.
This is covered in The try
Statement / Runtime Semantics: Evaluation in the specification, and perhaps more readably in try...catch
on MDN under "The finally
clause."
Note that the finally
can interrupt the return process, by either throwing an exception, or returning a new value. If it does either of those things, it wins over the return
in the try
(or catch
).
Side Note re your linked Java question: JavaScript's try
/catch
/finally
works just like Java's except: 1. You can only have one catch
block because exceptions aren't typed, and 2. JavaScript doesn't have Java's try-with-resources
statement.
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