What will happen when catch and finally block both return value, also when try and finally both return value in java


When catch and finally block both return value, method will ultimately return value returned by finally block irrespective of value returned by catch block.

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class ExceptionTest {
   public static void main(String[] args) {
          System.out.println("method return -> "+m());
   }
  
   static String m(){
          try{
                 int i=10/0; //will throw ArithmeticException
          }catch(ArithmeticException e){
                 return "catch";
          }finally{
                 return "finally";             
          }
         
   }
}
/*OUTPUT
method return -> finally
*/
In above program, i=10/0 will throw ArithmeticException and enter catch block to return "catch", but ultimately control will enter finally block to return "finally".



When try and finally block both return value, method will ultimately return value returned by finally block irrespective of value returned by try block.
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class ExceptionTest {
   public static void main(String[] args) {
          System.out.println("method return -> "+m());
   }
  
   static String m(){
          try{
                 int i=1;
                 return "try";
          }finally{
                 return "finally";             
          }
         
   }
}
/*OUTPUT
method return -> finally
*/
In above program, try block will "try", but ultimately control will enter finally block to return "finally".





RELATED LINKS>



eEdit
Must read for you :