Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
49
rated 0 times [  50] [ 1]  / answers: 1 / hits: 67256  / 14 Years ago, fri, october 1, 2010, 12:00:00

How does a return statement inside a try/catch block work?



function example() {
try {
return true;
}
finally {
return false;
}
}


I'm expecting the output of this function to be true, but instead it is false!


More From » return

 Answers
21

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:


function example() { 
var returnState = false; // initialization value is really up to the design
try {
returnState = true;
}
catch {
returnState = false;
}
finally {
return returnState;
}
}

Generally speaking you never want to have more than one return statement in a function, things like this are why.


[#95451] Tuesday, September 28, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zariahdiamondz

Total Points: 649
Total Questions: 109
Total Answers: 88

Location: Tajikistan
Member since Thu, Apr 14, 2022
2 Years ago
;