Skip to main content
Documents
Share
LinkedIn
Facebook
Twitter
Copy
Java keywords

finally Keyword in Java

The finally block in Java is a crucial part of exception handling. It is used to execute important code such as closing resources, regardless of whether an exception is thrown or not. The finally block always executes when the try block exits, ensuring that cleanup code runs.

Usage

The finally block is used in conjunction with try and catch blocks. It is placed after the catch block or directly after the try block if no catch block is present.

Syntax

try {
    // Code that may throw an exception
} catch (ExceptionType e) {
    // Code to handle the exception
} finally {
    // Code that will always execute
}

Examples

Example 1: Basic Usage

public class FinallyExample {
    public static void main(String[] args) {
        try {
            int data = 50 / 0; // This will throw an ArithmeticException
        } catch (ArithmeticException e) {
            System.out.println("Exception caught: " + e);
        } finally {
            System.out.println("Finally block is always executed");
        }
    }
}

In this example, an ArithmeticException is thrown and caught in the catch block. Regardless of the exception, the finally block executes and prints a message.

Example 2: Finally without Catch

public class FinallyWithoutCatchExample {
    public static void main(String[] args) {
        try {
            System.out.println("Inside try block");
        } finally {
            System.out.println("Finally block executed");
        }
    }
}

Here, no exception is thrown, and there is no catch block. The finally block executes after the try block, printing its message.

Example 3: Resource Cleanup

import java.io.*;

public class FinallyResourceExample {
    public static void main(String[] args) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("example.txt");
            // Perform file operations
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    System.out.println("Error closing file: " + e);
                }
            }
        }
    }
}

This example demonstrates using the finally block to ensure that a FileInputStream is closed, preventing resource leaks.

Tips and Best Practices

  • Resource Management: Use the finally block to close resources like files, database connections, or network sockets to avoid resource leaks.
  • Avoid Return Statements: Avoid placing return statements in the finally block, as it can obscure the flow of the program and make it harder to understand.
  • Nested Try-Finally: When working with multiple resources, consider using nested try-finally blocks to ensure each resource is properly closed.
    try {
        // Resource 1
    } finally {
        try {
            // Resource 2
        } finally {
            // Cleanup for Resource 2
        }
        // Cleanup for Resource 1
    }
  • Use Try-With-Resources: For managing resources, prefer the try-with-resources statement introduced in Java 7, which automatically closes resources.
    try (FileInputStream fis = new FileInputStream("example.txt")) {
        // Perform file operations
    } catch (IOException e) {
        System.out.println("Exception: " + e);
    }
  • Consistent Cleanup: Ensure that cleanup code is consistent and does not throw exceptions that might mask the original exception. Use nested try-catch within finally if necessary.
  • Execution Scenarios: Understand that the finally block always executes except in cases where the JVM exits during the try or catch blocks via calls like System.exit(), or in scenarios involving infinite loops or daemon threads.