Finally Block in Java
The finally block in Java is an optional section that follows try-catch blocks and contains code that runs regardless of whether an exception was thrown, c...
Code That Always Runs
The finally block in Java is an optional section that follows try-catch blocks and contains code that runs regardless of whether an exception was thrown, caught, or not thrown at all. The only circumstances under which finally does not execute are: calling System.exit(), a JVM crash, or an infinite loop inside the try block. In every other scenario—normal execution, exception thrown and caught, or exception thrown and not caught—the finally block runs before control leaves the try-catch-finally structure.
Primary Purpose: Resource Cleanup Before Java 7 introduced try-with-resources, the finally block was the standard way to release resources like database connections, file handles, and network sockets. By placing cleanup code in finally, you guarantee that resources are freed even if an exception interrupts the normal code path. This pattern prevents resource leaks, which are especially serious in server applications where connections are a limited pool shared across many requests.
Interaction with return Statements Finally introduces a subtle behavior when combined with return. If the try block returns a value and the finally block also returns a value, the finally block's return wins—it overwrites the try block's return. Similarly, if the try block throws an exception and the finally block also throws an exception, the original exception is lost and only the finally block's exception propagates. These behaviors mean you should almost never include return statements or throw statements inside finally.
Modern Alternative: try-with-resources Since Java 7, try-with-resources is the idiomatic way to handle resource cleanup. Resources declared in the try parentheses are closed automatically in reverse order when the block exits. This is safer than finally because the AutoCloseable.close() contract is well-defined, suppressed exceptions from close() are accessible, and there is no risk of a return inside finally overriding the try's return. Reserve finally for cleanup that cannot be expressed as an AutoCloseable.
Code Example: Connection conn = null; try { conn = getConnection(); // database operations return queryResult(conn); } catch (SQLException e) { System.err.println("DB error: " + e.getMessage()); return null; } finally { if (conn != null) { try { conn.close(); } catch (SQLException ignored) {} } System.out.println("Connection cleanup attempted."); }
Interview Tip: The classic finally interview puzzle asks whether a finally block runs after System.exit(). It does not—System.exit() terminates the JVM immediately, shutting down all threads and preventing any further code execution including finally blocks. Knowing this exception to the "finally always runs" rule impresses interviewers who expect candidates to know only the happy-path behavior.