Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execution of statements after try/catch block containing return

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.

like image 916
webspider Avatar asked Dec 20 '22 14:12

webspider


2 Answers

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.

like image 131
Jakub H Avatar answered Mar 15 '23 23:03

Jakub H


In case 2 you have a finally clause. It is executed after the try clause. So the execution order is:

  1. System.out.println(1);
  2. return;
  3. System.out.println(2);

And the "System.out.println(3);" is unreachable.

But in case 3 you have a cath clause. It is executed if there is a Exeption in the try clause. So there are to possible ways to go (with or without error on "System.out.println(1);")

First without error:

  1. System.out.println(1);
  2. return;

Second with error:

  1. System.out.println(1); (Throws a Execption)
  2. System.out.println(2); (Does not exit the code by return or throwing a new exeption)
  3. System.out.println(3); (after the try/catch)

PS.: In case 2 if you had a Exception on System.out.println(1); he would run the System.out.println(2); just before continue to throw the exception up to the stack trace...

like image 21
LgFranco Avatar answered Mar 15 '23 23:03

LgFranco