Search code examples
javatry-finally

Finally block overriding in java


Given below is my example about a simple finally block.

public class Ex2 {

    public static void main(String args[]) throws ArithmeticException {
        System.out.println(Ex2.myTestingFuncn());
    }

    public static int myTestingFuncn() {
        try {
            // first execution
            return 5;
        } finally {
            // second execution
            System.out.println("finally");
        }
    }
}

This results are
finally
5
as expected.


But when this happened finally block overrides try block's value.

try {
     // first execution
     return 5;
} finally {
     // second execution
     return 12;
}

Result : 12


How does this happens? I mean what is the order of these blocks execution?
Please help.
Thank you


Solution

  • In your first example, you use System.out.println 2 times. The first time when you call your function, the second time inside your function. So he will print "finally" first because this is the last block executed in your function. The reason 5 is printed as last is because that's the output of your called function. (after your function is executed, the output is 5) Because "finally' is printed inside your function, obviously it will display first (because it prints at run time) and after that, the actual output of your function being called will get printed. Don't use System.out.println inside your function. It might confuse you :)

    System.out.println means just print it out when you arrive at the place where the code is. ( = at run time)

    In your second example the return value itself gets overwritten. In the first example you only have 1 return value and a System.out.println statement, these have no impact on each other.

    Hope this helps.