Finally Block in Java
beginner· Exceptions · Error Handling
Problem
A finally block runs after a try or catch block finishes, even if that block exits by returning a value instead of falling through normally.
Return a value from inside a try block, and show that the finally block still runs before the method actually returns.
Input
value = "42"
Output
Cleanup: process() is finishing
Parsed value: 42
Java Program
Java
public class FinallyBlockDemo {
static String process(String value) {
try {
int num = Integer.parseInt(value);
return "Parsed value: " + num;
} catch (NumberFormatException e) {
return "Invalid number: " + value;
} finally {
System.out.println("Cleanup: process() is finishing"); // runs before the return actually completes
}
}
public static void main(String[] args) {
System.out.println(process("42"));
}
}Output
Cleanup: process() is finishing
Parsed value: 42
Core Logic
Returning from inside a try block doesn't skip its finally block — the return value is computed and held, the finally block runs, and only then does the method actually hand that value back.
How It Works
- 1
process("42")parses the string successfully and reachesreturn "Parsed value: " + num;inside thetryblock. - 2Java doesn't return immediately at that point — it first runs the
finallyblock, which prints the cleanup message. - 3Only after
finallyfinishes does the method actually return the value that was computed earlier. - 4
mainthen prints whateverprocess()returned, which is why the cleanup message appears before the parsed result.
For
value = "42", the cleanup message prints first from inside finally, then main prints the returned string, "Parsed value: 42".💡
Key Point: A return statement inside try doesn't exit the method immediately — finally always gets a chance to run first, which is exactly why it's a safe place for cleanup code regardless of how the try block exits.
Key Concepts
finally blockreturn inside tryexecution order