I have a suspicion that I'm using the finally
block incorrectly, and that I don't understand the fundamentals of its purpose...
function myFunc() {
try {
if (true) {
throw "An error";
}
} catch (e) {
alert (e);
return false;
} finally {
return true;
}
}
This function will run the catch
block, alert "An error", but then return true. Why doesn't it return false?
The
finally
block will always run, try returningtrue
after yourtry
blockRun this on your browser's console and it might give you the answer you're looking for.
Finally blocks execute when you leave the try block. In your code this happens when you return false. That sets the return value to false and attempts to exit the function. But first it has to exit the try block which triggers the finally and overwrites the return value to true.
It is considered by many to be a good programming practice to have a single return statement per function. Consider making a var retval at the beginning of your function and setting it to true or false as appropriate throughout your function and then structuring the code so that it falls correctly through to a single return at the bottom.