Interesting code snippet from reference [1]:
class Test
{
public static void main(String args[])
{
System.out.println(Test.test());
}
public static String test()
{
try {
System.out.println("try");
throw new Exception();
} catch(Exception e) {
System.out.println("catch");
return "return";
} finally {
System.out.println("finally");
return "return in finally";
}
}
}
Output:
try
catch
finally
return in finally
I changed a little and execute again:
public class Test {
public static void main(String args[]) {
System.out.println(Test.test());
}
public static String test() {
try {
System.out.println("try");
return "return normal";
} catch (Exception e) {
System.out.println("catch");
return "return";
} finally {
System.out.println("finally");
return "return in finally";
}
}
}
Output:
try
finally
return in finally
So, just like reference [1] another answer:
If the return in the try block is reached, it transfers control to the finally block, and the function eventually returns normally (not a throw).
If an exception occurs, but then the code reaches a return from the catch block, control is transferred to the finally block and the function eventually returns normally (not a throw).
[1] http://stackoverflow.com/questions/15225819/try-catch-finally-return-clarification-in-java