Java - finally block and cleanup code

Introduction

Typically, a finally block is used to do cleanup work.

try {
   // Obtain and use some resources here
}
finally {
  // Release the resources that were obtained in the try block
}

Demo

public class Main {
  public static void main(String[] args) {
    int x = 10, y = 0, z = 1;
    try {//from ww  w . ja v  a2  s  .c om
      System.out.println("Before dividing x by y.");
      z = x / y;
      System.out.println("After dividing x by y.");
    } catch (ArithmeticException e) {
      System.out.println("Inside catch block - 1.");
    } finally {
      System.out.println("Inside finally block - 1.");
    }

    try {
      System.out.println("Before setting z to 123.");
      z = 123;
      System.out.println("After setting z to 123.");
    } catch (Exception e) {
      System.out.println("Inside catch block - 2.");
    } finally {
      System.out.println("Inside finally block - 2.");
    }
    try {
      System.out.println("Inside try block - 3.");
    } finally {
      System.out.println("Inside finally block - 3.");
    }

    try {
      System.out.println("Before executing System.exit().");
      System.exit(0);
      System.out.println("After executing System.exit().");
    } finally {
      // This finally block will not be executed
      // because application exits in try block
      System.out.println("Inside finally block - 4.");
    }
  }
}

Result

Related Topic