A finally block always runs before control actually leaves the method, even when try ends with a return statement; the returned value is computed first, then finally runs, then the method exits.
static String greet() {
try {
return "hello";
} finally {
System.out.println("finally ran");
}
}
System.out.println("Result: " + greet());
finally ran
Result: hello
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-09-27