Java finally block With Example

Java finally block is used to keep clean up code like db connection,file closing etc.. .finally block will executes always after try-block exists.finally block always executes irrespective of exception raised or not.its better practice to put cleanup code in finally block . so our point is when some statements need to be executed whether exception raised or not so we need to place those statements in finally block.

Example 1:When exception is not raised
package com.java2study;
public class FinallyDemo {
 public static void main(String[] args) {
  try{
   System.out.println(1000/20);
  }catch(Exception e){
   e.printStackTrace();
  }finally{
System.out.println("finally block excuted always");
  }
 }
}
output
java.lang.ArithmeticException: / by zero
exception  code
finally block executes always
 at com.java2study.FInalyyDemo1.main(FInalyyDemo1.java:10)
Example 2:when exception is raised
package com.java2study;
public class FInalyyDemo1 {
 public static void main(String[] args) {
  try{
   System.out.println(10000/0);
  }catch(Exception e){
   e.printStackTrace();
   System.out.println("exception  code");
  }finally{
   System.out.println("finally block executes always");
  }

 }

}
output
java.lang.ArithmeticException: / by zero
 at com.java2study.FInalyyDemo1.main(FInalyyDemo1.java:10)
exception  code
finally block executes always
Here one point There is one situation finally block will not executes that is if you write System.exit(0); in try or catch block the finally block will not be executed.
Example1
package com.java2study;

public class FinallyDemo {

 /**
  * @java2study.com
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  
  try{
   System.out.println(1000/20);
   System.exit(0);
  }catch(Exception e){
   e.printStackTrace();
  }finally{
   System.out.println("finally block excuted always");
  }
 }
}
output
50
Example2
package com.java2study;
public class FInalyyDemo1 {
 public static void main(String[] args) {
  try{
   System.out.println(10000/0);
  }catch(Exception e){
   e.printStackTrace();
   System.out.println("exception  code");
   System.exit(0);
  }finally{
   System.out.println("finally block executes always");
  }

 }

}
java.lang.ArithmeticException: / by zero
exception  code
 at com.java2study.FInalyyDemo1.main(FInalyyDemo1.java:10)