Is finally block always get executed in Java?

JavaObject Oriented ProgrammingProgramming

Yes, the finally block is always get executed unless there is an abnormal program termination either resulting from a JVM crash or from a call to System.exit().

  • A finally block is always get executed whether the exception has occurred or not.
  • If an exception occurs like closing a file or DB connection, then the finally block is used to clean up the code.
  • We cannot say the finally block is always executes because sometimes if any statement like System.exit() or some similar code is written into try block then program will automatically terminate and the finally block will not be executed in this case.
  • A finally block will not execute due to other conditions like when JVM runs out of memory when our java process is killed forcefully from task manager or console when our machine shuts down due to power failure and deadlock condition in our try block.

Example 1

public class FinallyBlock {
   public static void main(String args[]){
      try {
         int a=10,b=30;
         int c = b/a;
         System.out.println(c);
      } catch(ArithmeticException ae){
         System.out.println(ae);
      } finally {
         System.out.println("finally block is always executed");
      }
   }
}

In the above example, the finally block always get executed if the exception has occurred or not.

Output

3
finally block is always executed

Example 2

public class FinallyBlock {
   public static void main(String args[]) {
      try {
         System.out.println("I am in try block");
         System.exit(1);
      } catch(Exception ex){
         ex.printStackTrace();
      } finally {
         System.out.println("I am in finally block");
      }
   }
}

In the above example, the finally block will not execute due to the System.exit(1) condition in the try block.

Output

I am in try block
raja
Published on 31-May-2019 16:30:08
Advertisements