4

I use this code to test try catch finally:

public class My{
    public static void main(String[] args) {
        System.out.println(fun1());
        System.out.println(fun2());
    }

    public static int fun1() {
        int a = 1;
        try {
            System.out.println(a / 0);
            a = 2;
        } catch (ArithmeticException e) {
            a = 3;
            return a;
        } finally {
            a = 4;
        }
        return a;

    }

    public static int fun2() {
        int a = 1;
        try {
            System.out.println(a / 0);
            a = 2;
        } catch (ArithmeticException e) {
            a = 3;
            return a;
        } finally {
            a = 4;
            return a;
        }

    }
}

output:

3
4

I know that finally will always run. I think the result of the two functions should be 4, but actually fun1() is 3 and the fun2() is 4. Why?

Sri
  • 437
  • 1
  • 4
  • 13
CR7
  • 125
  • 7
  • Duplicate of https://stackoverflow.com/questions/4264874/does-a-finally-block-run-even-if-you-throw-a-new-exception#:~:text=The%20finally%20block%20always%20executes,Exceptions%3A&text=Likewise%2C%20if%20the%20thread%20executing,application%20as%20a%20whole%20continues. – Ezio Mar 01 '21 at 05:16
  • Does this answer your question? [Multiple returns: Which one sets the final return value?](https://stackoverflow.com/questions/2309964/multiple-returns-which-one-sets-the-final-return-value) – Buh Buh Mar 01 '21 at 10:54

2 Answers2

3

This question is closely related, although it returns literals but not variables: Multiple returns: Which one sets the final return value?

In fun1 the return value is set via return a in the catch-block. At that line the value of a is copied into the return value. Changing a later does not change the return value.

In fun2 you have an explicit return in the finally block, so the return value in the finally block is what is returned.

Please read carefully through the answers in the question above for why you should not write code like that.

Another related question is this one: Returning from a finally block in Java

Daniel Junglas
  • 5,830
  • 1
  • 5
  • 22
2

In simple words when a function returns something it returns from the last executed return statement. in fun2() first return value is 3 which gets overridden by finally block's return value i.e 4. Whereas in fun1() method return is set to 3 from catch block and since the last line of func1() never gets executed hence 3 is returned.

hiren
  • 1,742
  • 13
  • 20