finally
TL;DR
- The
finallyblock is used to execute crucial cleanup code (like closing files or database connections). - It executes always, regardless of whether an exception was thrown in the
tryblock or caught in thecatchblock. - It is placed after the
catchblock(s).
Concept
In programming, resources like file streams, network sockets, or database connections must be explicitly closed to prevent memory/resource leaks.
If you open a file in a try block, and an exception occurs halfway through reading it, the rest of the try block is skipped. If your file.close() statement was at the bottom of the try block, it never runs!
The finally block guarantees execution. Even if a return statement is executed inside the try or catch block, the JVM will pause the return, execute the finally block, and then proceed with the return.
Examples
import java.io.FileReader;
import java.io.IOException;
public class FinallyExample {
public static void main(String[] args) {
FileReader reader = null;
try {
System.out.println("Opening file...");
reader = new FileReader("test.txt");
// Simulating an error
throw new RuntimeException("Something broke!");
} catch (IOException e) {
System.out.println("Caught IOException");
} catch (RuntimeException e) {
System.out.println("Caught RuntimeException: " + e.getMessage());
} finally {
System.out.println("Executing finally block: Closing resources.");
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
System.out.println("Failed to close file.");
}
}
}
}
Interview Questions
Q: Are there any scenarios where the finally block will NOT execute?
A: Yes. The finally block will not execute if:
System.exit()is called in thetryorcatchblock (which kills the JVM).- The JVM crashes entirely (e.g., a power outage or a fatal OS error).
- The thread executing the
try-catchblock is interrupted or killed (e.g., viaThread.stop()).
Q: Can you have a try block with a finally block, but no catch block?
A: Yes. A try block requires either a catch block, a finally block, or both. try { ... } finally { ... } is perfectly valid. It means “I don’t know how to handle the exception if it happens (so let it propagate up), but I still need to make sure I clean up my resources before it leaves this method.”