Understanding try catch finally with return and value that it returns

   Just before returning from the main block, the JVM has to make sure the finally block is executed, so it does that. The idea is to execute the finally block and then come back and execute the return statement from the main block. But if you have a return statement in the finally block, then it will be executed when the finally block is executed... which means that control never returns to the main block to complete the return statement.

1.      The JVM encounters the return statement in the main block. It pauses execution of the main block and checks for a finally clause.

2.      It executes the finally clause in its entirety, including its return statement.

3.      It never thus gets to complete the try block.

 Note, however, that the try block's return expression is evaluated and then discarded. This is important if it has side effects. 


package testPrep;

 public class newReturnTest {

       public int display(int i) {

              try {

                     if (i == 1) {

                           System.out.println("try");

                           return 0;

                     }

              } catch (NumberFormatException n) {

                     System.out.println("catch");

                     return 1;

              } finally {

                     System.out.println("finally");

                     // return 1;

              }

              return 9;

       }

 

       public static void main(String[] args) {

              // TODO Auto-generated method stub

 

              System.out.println(new newReturnTest().display(1));

 

       }

 

}

  o/p

  try

  finally

  0



========================

   public int display(int i) {

              try {

                     if (i == 1) {

                           System.out.println("try");

                           return 0;

                     }

              } catch (NumberFormatException n) {

                     System.out.println("catch");

                     return 1;

              } finally {

                     System.out.println("finally");

                     // return 1;

              }

              //return 9;

       }

o/p

try

finally

1

 

Comments