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?