Java finally

Introduction

Java provides the finally block. The finally block is part of Java’s exception handling mechanism and is designed to execute after a try block and any associated catch blocks. In most cases, the code inside the finally block runs whether an exception occurs or not, making it the ideal place for cleanup tasks.

Although modern Java also offers try-with-resources for automatically managing resources, understanding the finally block remains essential because it is widely used in existing Java applications and is a common interview topic.

What is the finally Block?

The finally block is a block of code that executes after the try and catch blocks.

Its primary purpose is to perform cleanup operations that must occur regardless of whether an exception is thrown.

Typical cleanup tasks include:

  • Closing files
  • Closing database connections
  • Closing sockets
  • Releasing memory
  • Unlocking resources
  • Flushing output streams

The finally block helps ensure that resources are released properly.

Why Use finally?

Using the finally block provides several benefits:

  • Ensures cleanup code always runs
  • Prevents resource leaks
  • Improves application reliability
  • Keeps cleanup logic separate from business logic
  • Simplifies maintenance
  • Works even when exceptions occur

Without a finally block, resources might remain open if an exception interrupts program execution.

Syntax of finally


try {
    // Risky code
} catch (Exception e) {
    // Handle exception
} finally {
    // Cleanup code
}

The finally block is optional, but when present, it executes after the try and catch blocks in most situations.

How finally Works?

The execution flow is as follows:

  1. Java executes the try block.
  2. If no exception occurs, the catch block is skipped.
  3. If an exception occurs, the matching catch block executes.
  4. The finally block executes after the try or catch block.
  5. Program execution then continues with the next statement.

This behavior makes finally ideal for releasing resources.

Example: finally Without an Exception


public class Main {
    public static void main(String[] args) {
        try {
            System.out.println("Inside try block.");
        } finally {
            System.out.println("Inside finally block.");
        }
        System.out.println("Program completed.");
    }
}

Output

Inside try block.
Inside finally block.
Program completed.

Since no exception occurs, the finally block still executes.

Example: finally With an Exception


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

Output

Exception handled.
Finally block executed.

The finally block executes even though an exception occurred.

finally Without a catch Block

A try block can be followed directly by a finally block.


public class Main {
    public static void main(String[] args) {
        try {
            System.out.println("Executing try block.");
        } finally {
            System.out.println("Executing finally block.");
        }
    }
}

In this case, any exception thrown in the try block will propagate to the caller after the finally block executes.

finally with return Statement

Even if a return statement is executed inside the try block, the finally block runs before the method returns.

Example


public class Main {
    static int test() {
        try {
            return 100;
        } finally {
            System.out.println("Finally executed.");
        }
    }
    public static void main(String[] args) {
        System.out.println(test());
    }
}

Output

Finally executed.
100

This demonstrates that the finally block executes before the method actually returns.

finally with throw Statement

The finally block also executes when an exception is explicitly thrown.


public class Main {
    public static void main(String[] args) {
        try {
            throw new RuntimeException("Custom exception");
        } finally {
            System.out.println("Cleanup completed.");
        }
    }
}

The finally block executes before the exception is propagated.

Common Uses of finally

The finally block is commonly used for resource cleanup.

Closing a File


FileReader reader = null;
try {
    reader = new FileReader("data.txt");
} catch (Exception e) {
    e.printStackTrace();
} finally {
    if (reader != null) {
        reader.close();
    }
}

Closing a Database Connection


Connection connection = null;
try {
    // Database operations
} finally {
    if (connection != null) {
        connection.close();
    }
}

These patterns were common before Java introduced try-with-resources.

try-with-resources vs finally

Java 7 introduced try-with-resources, which automatically closes resources.

try-with-resources Example


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Main {
    public static void main(String[] args) {
        try (BufferedReader reader =
                new BufferedReader(
                    new FileReader("data.txt"))) {
            System.out.println(reader.readLine());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In many situations, try-with-resources is preferred because it automatically closes resources, reducing boilerplate code.

When finally May Not Execute

Although the finally block executes in most cases, there are rare situations where it may not run.

Examples include:

  • Calling System.exit()
  • JVM crash
  • Power failure
  • Operating system shutdown
  • Hardware failure

Example:


try {
    System.exit(0);
} finally {
    System.out.println("This will not execute.");
}

Since the JVM terminates immediately, the finally block is skipped.

Real-Life Example

Suppose an online banking application opens a database connection to process a transaction.


public class BankingApp {
    public static void main(String[] args) {
        try {
            System.out.println("Processing transaction...");
        } catch (Exception e) {
            System.out.println("Transaction failed.");
        } finally {
            System.out.println("Closing database connection.");
        }
    }
}

Output

Processing transaction…
Closing database connection.

Regardless of whether the transaction succeeds or fails, the database connection is closed.

Advantages of finally

  • Ensures cleanup code executes
  • Prevents resource leaks
  • Improves reliability
  • Simplifies maintenance
  • Works with both handled and unhandled exceptions
  • Separates cleanup logic from business logic

Common Mistakes

1. Writing Business Logic Inside finally

The finally block should contain cleanup code, not application logic.

2. Ignoring try-with-resources

For resources that implement AutoCloseable, prefer try-with-resources over manually closing them in finally.

3. Throwing Exceptions from finally

Throwing a new exception inside finally can suppress the original exception and make debugging more difficult.

4. Assuming finally Always Executes

Remember that finally may not execute if the JVM terminates abruptly, such as through System.exit().

5. Forgetting Null Checks

Always check whether a resource is null before attempting to close it when using manual cleanup.

Best Practices

📖
Best Practices:
  • Use finally only for cleanup operations.
  • Prefer try-with-resources for managing files, streams, and database connections.
  • Avoid placing complex logic inside finally.
  • Do not throw exceptions from finally unless absolutely necessary.
  • Keep the finally block short and focused.
  • Release all acquired resources promptly.
  • Handle exceptions during cleanup if required.

Conclusion

The Java finally block is a key part of Java’s exception handling mechanism. It ensures that cleanup code runs after a try block, whether or not an exception occurs. This makes it ideal for releasing resources such as files, streams, database connections, and network sockets.

Related Java Tutorials