RETURN STATEMENT WITH TRY, CATCH, FINALLY

Return statement with try, catch, finally


    Example 1:

     
                    
                 public class Test
                 {
                    public static void main(String []args)
                    {
                       int i  = callTest();
                       System.out.println(i);
                    }
                    private static int callTest()
                    {
                       try 
                       {
                          System.out.println("in the try block");
                          String i  = "9";
                          int k  = Integer.parseInt(i);
                          return k;
                       }
                       catch (ArithmeticException ex)
                       {
                          System.out.println("In the catch block");
                          return 1000;
                       }
                       finally 
                       {
                          System.out.println("In the finally block");
                          return 3;
                       }
                    }
                 }                

    Output:

    In the try block In the finally block 3
    Note

    not any error statement in the try block so return k in finally block, finally block return value override try return value than return (3) value of finally.

    Case 1:

      Change in this program exception occur than catch block is exception than go to finally block and override catch return value with finally return value and return finally value.

    Case 2:

      if mention return statement after finally block than unreachable code error occur.