Finally block in java


Contents of page :
  • try or try-catch block can be followed by finally block >
  • Features of finally >
  • finally block is not executed in following scenarios >
  • Programming time - we will create following programs to demonstrate finally block in java >
  • Program 1 to show finally block is executed when exception is not thrown.
    Program 2 to show finally block is executed when exception is thrown, in this case catch and finally both blocks are executed.
  • Program 3 to show finally block is executed when exception is thrown and not handled properly, in this case catch blocks does not executes, finally block executes alone.
  • Program 4 to show finally is not executed when System.exit is called.
    • Bit more about System.exit(n) method >
  • Program 5 to show what will happen when catch and finally both return some value.
  • Application of finally block in java programs >

try or try-catch block can be followed by finally block >
  • try-finally block, or
try{
             //Code to be enclosed in try-finally block
      }finally{
      }   

  • try-catch-finally block.
      try{
             //Code to be enclosed in try-catch-finally block
      }catch(Exception e){
      }finally{
      }

finally block can can only exist if try or try-catch block is there, finally block can’t be used alone in java.
Using only finally block will cause compilation error
      finally{
             //only finally block will cause compilation error
      }



Features of finally >
  • finally block is always executed irrespective of exception is thrown or not.
  • finally is keyword in java.
  • finally block is optional in java, we may use it or not.


finally block is not executed in following scenarios >
  • finally is not executed when System.exit is called.
  • if in case JVM crashes because of some java.util.Error.


Programming time - we will create following programs to demonstrate finally block in java >

Program 1 to show finally block is executed when exception is not thrown.

Program 2 to show finally block is executed when exception is thrown, in this case catch and finally both blocks are executed.

Program 3 to show finally block is executed when exception is thrown and not handled properly, in this case catch blocks does not executes, finally block executes alone.

Program 4 to show finally is not executed when System.exit is called.

Program 5 to show what will happen when catch and finally both return some value.


Program 1 to show finally block is executed when exception is not thrown.
package finally1;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class ExceptionTest {
   public static void main(String[] args) {
         
          try{
                 int i=10/1;
          }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
finally block executed
code after try-catch-finally block
*/




Program 2 to show finally block is executed when exception is thrown, in this case catch and finally both blocks are executed.
package finally2;
/** 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
*/



Program 3 to show finally block is executed when exception is thrown and not handled properly, in this case catch blocks does not executes, finally block executes alone.
package finally3;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class ExceptionTest {
   public static void main(String[] args) {
         
          try{
                 int i=10/0; //will throw ArithmeticException
          }catch(IndexOutOfBoundsException e){
                 System.out.println("IndexOutOfBoundsException handled in catch block");
          }
          finally{
                 System.out.println("finally block executed");             
          }
          System.out.println("code after try-catch-finally block");
   }
}
/*OUTPUT
finally block executed
Exception in thread "main" java.lang.ArithmeticException: / by zero
   at finally3.ExceptionTest.main(ExceptionTest.java:7)
*/

It’s important to note in above program that finally block was executed but catch block didn’t because Exception wasn’t handled properly in above program - program throwed ArithmeticException but we were handing IndexOutOfBoundsException.
Also, sysout statement after try-catch-finally block wasn’t executed.


Program 4 to show finally is not executed when System.exit is called.
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
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.


Bit more about System.exit(n) method >
  • System.exit terminates JVM.
  • Parameter
    • Passing zero as parameter means normal termination &
    • Passing non-zero as parameter means abnormal termination.
  • System.exit(n) internally calls Runtime.getRuntime().exit(n)



Program 5 to show what will happen when catch and finally both return some value.



Application of finally block in java programs >
  • We may use finally block to execute code for database connection closing, because closing connection in try or catch block may not be safe.
    • Why closing connection in try block may not be safe?
    • Because exception may be thrown in try block before reaching connection closing statement.

    • Why closing connection in catch block may not be safe?
    • Because inappropriate exception may be thrown in try block and we might not enter catch block to close connection.







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 :