Return from try block to try finally block

I have two pieces of code in both cases, I return from try and finally block. The first one works fine, and also prints, finally, and later gives a compile-time error in a line labeled line1.

1st snipp

class abc {
public static void main(String args[]) {
    System.out.println("1");
    try {
        return;
    } catch (Exception ex) {
        System.out.println("Inside catch");
    } finally {
        System.out.println("2");
    }
    System.out.println("3");
}
}

2nd snipp (compile-time error)

class Test11 {
public static void main(String[] args) {
    Test11 test = new Test11();
    System.out.println("1");
    try {
        return;
    } finally {
        System.out.println("2");
    }
    // COMPILER ERROR
    // System.out.println(test instanceof Test11);// line 1
}
}

Answer: The reason for the 1st fragment is the execution path followed by the catch block, but there is no such path in the second fragment, so the statement after it is finally unavailable.

+4
source share
1 answer

line 1 is unreachable. Because there is no way to go to line1.

, try. .

catch, , try-, 1

+1

Source: https://habr.com/ru/post/1671106/


All Articles