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?