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
Release: 2023-09-17 15:05:07
forward
1112 people have browsed it

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

Output

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

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!

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