If I run the following code:
try{
return false;
} catch(Exception e){
e.printStackTrace();
}
finally{
return true;
}
why does it return true?
If I run the following code:
try{
return false;
} catch(Exception e){
e.printStackTrace();
}
finally{
return true;
}
why does it return true?
From the Java Language Specification section 14.20.2
(my italics). A return
is one kind of "abrupt completion", in other words the return
from the finally
overrules the one from inside the try
.
It returns true
because whenever a finally
block completes abruptly, either by return
-ing or by throwing an exception, that completion supersedes any previous return-value or exception. (See §14.20.2 "Execution of try-finally
and try-catch-finally
" in the Java Language Specification, Java SE 7 Edition.)
Because no matter what happens in the try catch portion, the finally block will always do what you ask so in this case it returns true. Just remove the finally statement and it should return false.
Finally block doesnot execute when try or catch block terminate by calling System.exit
function. Similarly if the thread executing try catch dies while executing try or catch block then finally block may not execute.
So its likely that your try catch finally block will almost always return true even if your try block is returning false .