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
return
statement in thefinally
block is usually a bad idea.What happens in your example is the following. The
return
statement in thetry
block is executed. However, thefinally
block must always be executed so it is executed after thecatch
block finishes. Thereturn
statement occurring there overwrites the result of the previousreturn
statement, and so the method returns the second result.Similarly a
finally
block usually should not throw an exception. That's why the warning says that thefinally
block should complete normally, that is, withoutreturn
or throwing an exception.