Home > Java > javaTutorial > body text

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

WBOY
Release: 2023-08-29 22:17:13
forward
1044 people have browsed it

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());
   }
}
Copy after login

Output

1
Copy after login

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());
   }
}
Copy after login

Output

30
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!