Execution of statements after try/catch block containing return

webspider picture webspider · May 27, 2014 · Viewed 8.1k times · Source

There are three cases to be considered :

Case 1:

public class Test {

    public static void main(String[] args) {
                System.out.println(1);
                System.out.println(2);
                return;
                System.out.println(3);
    }
}

Case 2:

public class Test {

    public static void main(String[] args) {

        try{
            System.out.println(1);
            return;
        }finally{
            System.out.println(2);
        }
        System.out.println(3);
    }
}

Case 3:

public class Test {

    public static void main(String[] args) {
        try{
            System.out.println(1);
            return;
        }catch(Exception e){
            System.out.println(2);
        }
        System.out.println(3);
    }
}

I understand that in case 1 statement System.out.println(3) is unreachable that's why it is a compiler error, but why compiler does not shows any error in case 3.

Also note that it is even a compiler error in case 2.

Answer

Jakub H picture Jakub H · May 27, 2014

Case 3:

If exception is raised than all your code is available and it prints 1,2,3. That's the reason why you don't have any error (unreachable code) there.

Case 2:

In this case no matter what you won't reach System.out.println(3), because you always return from main method.