What if your program could always clean up after itself, no matter what goes wrong?
Why Finally block in Java? - Purpose & Use Cases
Start learning this pattern below
Jump into concepts and practice - no test required
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.
Practice
What is the main purpose of the finally block in Java exception handling?
Solution
Step 1: Understand the role of try-catch-finally
The try block contains code that might throw exceptions, catch handles them, and finally runs code after both.Step 2: Identify the purpose of finally
The finally block always executes, whether an exception occurs or not, to finalize or clean up resources.Final Answer:
To execute code regardless of whether an exception occurs or not -> Option CQuick Check:
finally always runs = B [OK]
- Thinking finally only runs if an exception occurs
- Confusing finally with catch block
- Assuming finally can catch exceptions
Which of the following is the correct syntax to add a finally block after a try-catch in Java?
try {
// code
} catch(Exception e) {
// handle
} ??? {
// cleanup
}Solution
Step 1: Recall Java exception syntax
Java uses the keywordfinallyto define the block that runs after try and catch.Step 2: Match the correct keyword
Among options, onlyfinallyis the valid keyword for this block.Final Answer:
finally -> Option AQuick Check:
finally keyword syntax = D [OK]
- Using 'final' instead of 'finally'
- Confusing with 'finalize' method
- Using invalid keywords like 'end'
What will be the output of the following Java code?
public class Test {
public static void main(String[] args) {
try {
System.out.print("Try-");
return;
} catch(Exception e) {
System.out.print("Catch-");
} finally {
System.out.print("Finally");
}
System.out.print("End");
}
}Solution
Step 1: Analyze try block execution
The try block prints "Try-" and then returns, so normally method would exit here.Step 2: Check finally block behavior with return
Even with return, finally block executes, printing "Finally" before method exits.Step 3: Confirm code after finally
Code after finally (System.out.print("End")) is unreachable due to return, so not executed.Final Answer:
Try-Finally -> Option DQuick Check:
finally runs even after return = C [OK]
- Assuming code after finally runs after return
- Thinking catch block runs without exception
- Ignoring finally block execution
Identify the error in the following code snippet:
try {
int a = 5 / 0;
} finally {
System.out.println("Cleanup");
}Solution
Step 1: Check try-finally syntax rules
Java allows try-finally without catch; try must be followed by catch or/and finally.Step 2: Analyze exception handling
Division by zero throws ArithmeticException at runtime, finally executes cleanup, then exception propagates to caller.Step 3: Confirm no error
The code compiles and runs validly (prints "Cleanup" before propagating exception); no syntax or structural error.Final Answer:
No error, code is valid -> Option AQuick Check:
try-finally valid without catch = D [OK]
- Thinking finally requires catch block
- Confusing runtime exception with syntax error
- Believing finally alone causes compile error
Consider this method:
public static int test() {
try {
System.out.print("Try-");
throw new RuntimeException();
} catch(RuntimeException e) {
System.out.print("Catch-");
return 1;
} finally {
System.out.print("Finally-");
return 2;
}
}What will System.out.print(test()); output?
Solution
Step 1: Trace try block execution
Try prints "Try-" then throws RuntimeException.Step 2: Catch block handles exception
Catch prints "Catch-" and returns 1, but return is not final yet.Step 3: finally block overrides return
Finally prints "Finally-" and returns 2, overriding previous return 1.Step 4: Combine printed output and return value
Printed output is "Try-Catch-Finally-" and method returns 2, so print(test()) outputs "2" after prints.Final Answer:
Try-Catch-Finally-2 -> Option BQuick Check:
finally return overrides catch return = A [OK]
- Ignoring finally return overriding catch return
- Assuming catch return is final
- Missing printed output before return
