Finally Block

The finally block in Java is used to execute important code such as closing connections, streams, etc. It is executed regardless of whether an exception is handled or not.

Using the Finally Block

The finally block is always executed after the try and catch blocks:


public class Main {
    public static void main(String[] args) {
        try {
            int[] numbers = {1, 2, 3};
            System.out.println(numbers[5]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index out of bounds!");
        } finally {
            System.out.println("This block is always executed.");
        }
    }
}
      

In this example, the finally block is executed regardless of the exception thrown.

Finally Block Without Catch

You can use a finally block without a catch block:


public class Main {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;
        } finally {
            System.out.println("Finally block is executed.");
        }
    }
}
      

In this example, the finally block is executed even though there is no catch block.

Common Uses of Finally Block

  • Closing Resources – Close database connections, file streams, etc.
  • Cleanup – Perform cleanup operations like deleting temporary files.

Continue exploring our intermediate tutorials to learn more about Java programming.

Scroll to Top