Exceptions: finally runs even when the try block returns

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.

Code
static String greet() {
    try {
        return "hello";
    } finally {
        System.out.println("finally ran");
    }
}
System.out.println("Result: " + greet());
Output
finally ran
Result: hello
Advertisement
More in JAVA

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

© Java Coding Hub · About · Contact · Privacy · Terms