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
1142 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:
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
Latest Issues
Install JAVA
From 1970-01-01 08:00:00
0
0
0
Unable to install java
From 1970-01-01 08:00:00
0
0
0
Can java be used as the backend of the web?
From 1970-01-01 08:00:00
0
0
0
Is this in Java language?
From 1970-01-01 08:00:00
0
0
0
Help: JAVA encrypted data PHP decryption
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template