I was wondering, is it good practice to return from try block?
package debug;
/**
*
* @author Owner
*/
public class Main {
public static void main(String[] args) {
System.out.println(fun());
}
static boolean cleanup() {
// Fail to cleanup.
return false;
}
static boolean fun() {
boolean everything_is_fine = true;
try {
System.out.println("open file stream");
return everything_is_fine;
} finally {
everything_is_fine = cleanup();
}
}
}
I first thought false will be printed. However, here is the output :
open file stream
true
As you can see, if I am having return statement within try block, I will miss the fail status during finally cleanup.
Shall I have the code as :
static boolean fun() {
boolean everything_is_fine = true;
try {
System.out.println("open file stream");
} finally {
everything_is_fine = cleanup();
}
return everything_is_fine;
}
As long as the returned value from finally block is concerned, shall I avoid return from try?
Your suggested code (at the end of the question) is fine. You can return from the
finallyblock, but you should not – for example eclipse shows a warning “finally block does not complete normally”.In fact, the
try/finallyaren’t directly related to thereturn. It seems so here, because it is the only construct in the method, but you can have other code after that (for example – event notifications), and then return.As for your question – you can’t change the value of the returned variable in the
finallyblock if it is already returned. So don’t return fromtry.