In Java there are always the little things which get you thinking :D
So the question is: will the finally
part in a try
and catch
block be executed even after a return
. This means, that a method will be left before the finally statement.
Lets try it out:
package me.kamwo.examples;
import org.junit.Test;
/**
* Created by kwozniak on 07.05.15.
*/
public class FinallyTest {
@Test
public void testFinally() {
System.out.println("result: " + result());
}
public String result() {
try {
return "something";
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("Finally executed!");
}
return "Fail.";
}
}
And here are the results:
Finally executed!
result: something
Conclusion
The finally block will always be executed even after a return statement.