Home >Java >javaTutorial >In Java, after the return statement in a method is executed, will the finally block be executed?

In Java, after the return statement in a method is executed, will the finally block be executed?

PHPz
PHPzforward
2023-09-17 15:05:071095browse

In Java, after the return statement in a method is executed, will the finally block be executed?

Yes, the finally block will be executed even after the return statement in the method.

In Java, the finally block will be executed regardless of whether an exception occurs. If we explicitly call the System.exit() method in the finally block, then only it will not be executed. There are rare situations where finally will not be executed, such as JVM crash, power failure, software crash, etc. Except for these cases, the finally block will always be executed.

Example

public class FinallyBlockAfterReturnTest {
   public static void main(String[] args) {
      System.out.println(<strong>count()</strong>);
   }
   public static int count() {
      try {
<strong>         return 1;
</strong>      } catch(Exception e) {
<strong>         return 2;
</strong>      } finally {
         System.out.println("Finally block will execute even after a return statement in a method");
      }
   }
}

Output

Finally block will always excute even after a return statement in a method
1

The above is the detailed content of In Java, after the return statement in a method is executed, will the finally block be executed?. 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