Can we have a return statement in the catch or, finally blocks in Java?

JavaObject Oriented ProgrammingProgramming

Yes, we can write a return statement of the method in catch and finally block.

  • There is a situation where a method will have a return type and we can return some value at any part of the method based on the conditions.
  • If we return a value in the catch block and we can return a value at the end of the method, the code will execute successfully.
  • If we return a value in the catch block and we can write a statement at the end of the method after return a value, the code will not execute so it became unreachable code as we know Java does not support unreachable codes.
  • If we return a value in the final block and no need of keeping a return value at the end of the method.

Example 1

public class CatchReturn {
   int calc() {
      try {
         int x=12/0;
      } catch (Exception e) {
         return 1;
      }
      return 10;
   }
   public static void main(String[] args) {
      CatchReturn cr = new CatchReturn();
      System.out.println(cr.calc());
   }
}

Output

1

Example 2

public class FinallyReturn {
   int calc() {
      try {
         return 10;
      } catch(Exception e) {
         return 20;
      } finally {
         return 30;
      }
   }
   public static void main(String[] args) {
      FinallyReturn fr = new FinallyReturn();
      System.out.println(fr.calc());
   }
}

Output

30
raja
Published on 30-May-2019 15:51:02
Advertisements