Will a finally block execute after a return statement in a method in Java?


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

The finally block will always execute even an exception occurred or not in Java. If we call the System.exit() method explicitly in the finally block then only it will not be executed. There are few situations where the finally will not be executed like JVM crash, power failure, software crash and etc. Other than these conditions, the finally block will be always executed.

Example

public class FinallyBlockAfterReturnTest {
   public static void main(String[] args) {
      System.out.println(count());
   }
   public static int count() { 
      try {
         return 1;
      } catch(Exception e) {
         return 2;
      } 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
raja
Published on 09-Aug-2019 13:08:22
Advertisements