Finally Block in Java — Java Technical Interview Questions & Answers
Finally Block in Java
Finally Block in Java
- finally runs after try (and catch, if any). Use it for cleanup: close file, close connection. It runs whether an error happened or not — that is the point.
- try-with-resources often replaces manual finally for Closeable things, but viva still asks finally. A return inside try still hits finally before leaving.
- Don’t put the real business result only in finally. finally is cleanup, not the main logic.
- Let's take this on the board with one tiny Main class — no extra files. Finally Block in Java — output: Cannot divide then finally always. catch handles /0; finally still runs. Start from main, go line by line, and stop at each print. That output is the proof for Finally Block.
Technical Interview Tip: Say: finally always runs for cleanup. Then mention try-with-resources as the modern close.
Code Examples for Finally Block in Java
Example
public class Main {
public static void main(String[] args) {
try {
System.out.println("try");
} finally {
System.out.println("finally always");
}
}
}Finally Block in Java — output: Cannot divide then finally always. catch handles /0; finally still runs.
How to Explain Finally Block in Java to an Interviewer
When does finally run?
After try/catch Error or no error
What is finally for?
Cleanup Close file / connection