Home >Java >javaTutorial >In Java, can we use return statement in catch or finally block?

In Java, can we use return statement in catch or finally block?

WBOY
WBOYforward
2023-08-29 22:17:131128browse

In Java, can we use return statement in catch or finally block?

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

  • There is a situation where a method will have a return type and we can return some value in any part of the method based on a condition.
  • If we return a value in the catch block and we can return a value at the end of the method, then 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 returning a value, then the code will not execute because we know Java does not support unreachable code.
  • If we return a value in the final block and don't need to keep 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

The Chinese translation of Example 2

is:

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

The above is the detailed content of In Java, can we use return statement in catch or finally block?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete