This was an interview question:
public class Demo {
public static void main(String[] args) {
System.out.println(foo());
}
static String foo() {
try {
return "try ...";
} catch (Exception e) {
return "catch ...";
} finally {
return "finally ..."; //got as result
}
}
}
My question is why there are no compile time errors. When I have the return statement in my finally block, it is bound to return from finally instead of try and catch block. I tried to compile this code with -Xlint option, it gives a warning as.
warning: [finally] finally clause cannot complete normally
It does not give a compilation error because it is allowed by the Java Language Specification. However, it gives a warning message because including a
returnstatement in thefinallyblock is usually a bad idea.What happens in your example is the following. The
returnstatement in thetryblock is executed. However, thefinallyblock must always be executed so it is executed after thecatchblock finishes. Thereturnstatement occurring there overwrites the result of the previousreturnstatement, and so the method returns the second result.Similarly a
finallyblock usually should not throw an exception. That's why the warning says that thefinallyblock should complete normally, that is, withoutreturnor throwing an exception.