Does finally block always gets executed in java




Contents of page :


1) Does finally block always gets executed in java?
No, it's not mandatory, lets discuss scenarios where finally block is not executed in java.


2) finally block is executed in following scenarios in java >

2.1) Program to show finally block is executed when exception is thrown, in this case catch and finally both blocks are executed >


/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class ExceptionTest {
   public static void main(String[] args) {
         
          try{
                 int i=10/0; //will throw ArithmeticException
          }catch(ArithmeticException e){
                 System.out.println("ArithmeticException handled in catch block");
          }
          finally{
                 System.out.println("finally block executed");             
          }
      System.out.println("code after try-catch-finally block");
   }
}
/*OUTPUT
ArithmeticException handled in catch block
finally block executed
code after try-catch-finally block
*/


For more details read : Finally block in java


3) finally block is not executed in following scenarios in java >
  • 1) finally is not executed when System.exit is called.
  • 2) Or another case may be there when there is infinite loop in try block.
  • 3) if in case JVM crashes because of some java.util.Error.


3.1) Program 1 to show when finally is not executed when System.exit is called in java.
public class ExceptionTest {
   public static void main(String[] args) {
          try{
                 System.out.println("in try block");
                 System.exit(0);
          }finally{
                 System.out.println("finally block executed");             
          }
   }
}
/*OUTPUT
in try block
*/
In the above program, finally block is not executed when System.exit is called.


3.2) Program 2 to show when finally block is not executed in java >
public class FinallyExample {
   public static void main(String[] args) {
      try{
            
             /* Infinite for loop*/
             for(;;){
                   System.out.println("in try block - Infinite for loop");
             }
      }finally{
             System.out.println("finally block executed");         
      }
   }
}


In above program there is infinite for loop is there in try block which will never end and finally block will never be executed.

Also read about System.exit(n) method > xxxd


Also read Program to show what will happen when catch and finally both return some value. Click here.






RELATED LINKS>








EXCEPTIONS - Top 60 interview questions and answers in java for fresher and experienced - 30 important OUTPUT questions Set-2 > Q26- Q60



eEdit
Must read for you :