A finally block guarantees that cleanup code runs whether the try block completes normally or throws an exception, which makes it the natural place for releasing resources like streams, connections, or locks that must never be left open.
Key Points: • finally executes after the try, and any matching catch, regardless of whether an exception was thrown, caught, or propagated further. • It's most commonly used for resource cleanup, such as closing files, database connections, or network sockets, to prevent resource leaks even on the error path. • Modern Java code often replaces manual finally-based cleanup with try-with-resources for anything implementing AutoCloseable, since it's less error-prone. • finally still has value beyond simple resource closing, such as releasing a lock acquired manually or resetting shared state regardless of outcome.
Example: When reading a file manually with a FileInputStream, wrapping the read logic in try and closing the stream in finally ensures the file handle is released even if an IOException interrupts the read partway through.
Code Example:
FileInputStream in = null;
try {
in = new FileInputStream("data.txt");
// read data
} catch (IOException e) {
// handle error
} finally {
if (in != null) {
in.close();
}
}Interview Tip: A concise interview answer is:
"Yes — I've used finally most often for resource cleanup, like closing a file stream or database connection, since it's guaranteed to run whether or not an exception occurs. These days I'd typically prefer try-with-resources for anything AutoCloseable, but finally is still useful for cleanup that doesn't fit that pattern, like releasing a manually acquired lock."