What if your program could always clean up after itself, no matter what goes wrong?
Why Finally block in Java? - Purpose & Use Cases
Imagine you are writing a program that opens a file to read data. You write code to open the file and then read from it. But what if an error happens while reading? You might forget to close the file, leaving it open and causing problems later.
Manually closing resources like files or connections after every operation is easy to forget. If an error occurs, your program might skip the closing step, causing memory leaks or locked files. This makes your program unreliable and hard to fix.
The finally block is a special part of Java's error handling that always runs, no matter what. It lets you put cleanup code like closing files or releasing resources there, so you never forget to do it, even if errors happen.
try {
openFile();
readFile();
closeFile();
} catch (Exception e) {
handleError(e);
// forgot to closeFile() here
}try {
openFile();
readFile();
} catch (Exception e) {
handleError(e);
} finally {
closeFile();
}It ensures your cleanup code always runs, making your programs safer and more reliable.
Think of it like locking your door every time you leave the house, no matter what happens. The finally block is your automatic lock that never forgets.
The finally block always runs after try/catch.
It is perfect for cleanup tasks like closing files or connections.
It helps prevent resource leaks and keeps programs stable.