JAVA

Java Finally Block


What is finally block?

  • It is used to define a block of code that will be executed regardless of whether an exception is thrown or not. 
  • The finally block is often used for cleanup or resource release tasks, ensuring that certain operations are performed regardless of the outcome of the try and catch blocks.

Syntax

try {
    // Code that may cause an exception
} catch (ExceptionType e) {
    // Code to handle the exception
} finally {
    // Code that will be executed regardless of whether an exception occurs or not
}

Example

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

class FileReadExample {

    public static void main(String[] args) {
        // Specify the file path
        String filePath = "example.txt";
        BufferedReader reader = null;

        try {
            // Open a file for reading
            reader = new BufferedReader(new FileReader(filePath));

            // Read data from the file (this could potentially throw an IOException)
            String line = reader.readLine();
            System.out.println("Read from file: " + line);

		} catch (IOException e) {
            // Handle IOException (e.g., log the exception or take appropriate action)
            System.err.println("IOException: " + e.getMessage());
        } finally {
            try {
                // Close the file in the finally block to ensure it is always closed
                if (reader != null) {
                    reader.close();
                    System.out.println("File closed successfully.");
                }
            } catch (IOException e) {
                // Handle IOException during the closing of the file
                System.err.println("Error closing file: " + e.getMessage());
            }
        }
    }
}

Note: 

  • The finally block contains code that must be executed regardless of whether an exception occurred in the try block or not.
  • In this example, the finally block is used to close the file (BufferedReader) to ensure that resources are released properly.
  • Closing the file in the finally block is crucial because it guarantees that the file will be closed, even if an exception occurs in the try block. This is essential for resource cleanup and preventing resource leaks.