How does a return statement inside a try/catch block work?
JavaScript
x
9
1
function example() {
2
try {
3
return true;
4
}
5
finally {
6
return false;
7
}
8
}
9
I’m expecting the output of this function to be true
, but instead it is false
!
Advertisement
Answer
Finally always executes. That’s what it’s for, which means its return value gets used in your case.
You’ll want to change your code so it’s more like this:
JavaScript
1
13
13
1
function example() {
2
var returnState = false; // initialization value is really up to the design
3
try {
4
returnState = true;
5
}
6
catch {
7
returnState = false;
8
}
9
finally {
10
return returnState;
11
}
12
}
13
Generally speaking you never want to have more than one return statement in a function, things like this are why.