I was at an interview yesterday and got something like this snippet as a test.
Apologies for the lack of tabs,
whatever I try to put them in,
wordpress defeats me.
public class ExceptionTest {
public String method1(){
try {
return method2();
}
catch (Exception e) {
return "method 1";
}
}
public String method2() throws Exception {
try {
throw new Exception();
}
finally {
return "method 2";
}
}
public static void main(String [] argz) {
ExceptionTest et = new ExceptionTest();
System.out.println(et.method1());
}
}
I was asked if I thought the finally block in method2 would execute before the catch in method1? So I puzzle over that for a while,
trying to determine how the stack would unroll, particularly in light of the finally block returning a value. I think my guess was pretty good.
I went ahead and tested it to see what actually did happen, and it turns out that returning from a finally block as in this example generates a compiler warning, and gleefully prevents the catch block from even executing, resulting in the program printing out “method2”. If the return is removed from the finally block, finally still executes before the catch block, as expected so that it can clean up the local state of that stack frame, and the program prints out “method1”.
You’re such a nerd.