Executing statements after try / catch block with return

There are three cases:

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 if statement 1 is System.out.println(3)unreachable, why is it a compiler error, but why does the compiler not show errors in case 3.

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

+4
source share
4 answers

Case 3:

If an exception occurs than all of your code and it prints 1,2,3. This is the reason you have no error (unreachable code).

Case 2:

In this case, no matter what you do not achieve System.out.println(3), because you always return from the method main.

+5

2 finally. try. , :

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

"System.out.println(3);" .

3 cath. , try Exeption. , ( "System.out.println(1);" )

:

  • System.out.println(1);
  • ;

:

  • System.out.println(1); ( Execption)
  • System.out.println(2); ( )
  • System.out.println(3); ( /)

PS: 2, System.out.println(1); System.out.println(2); , ...

+3

3, println (1) RuntimeException, println (2), println (3). , println (3) .

+1

1 , , , 3 System.out.println(3),

3:

System.out.println(1), catch System.out.println(2), System.out.println(3)

:

try, System.out.println(1) System.out.println(3)

, try, println (1), , println (1)

, - ,

public class Test {

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

, , System.out.println(1), try System.out.println(1) , try try-catch

+1

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


All Articles