100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Java

finally Block in Java

Learn how the finally block guarantees cleanup code execution in Java, even when exceptions or return statements are involved.

Exception HandlingBeginner7 min readJul 7, 2026
Analogies

1. Introduction

The finally block is an optional part of a try statement that always executes after the try block (and any matching catch block) completes, regardless of whether an exception was thrown or caught. It is most commonly used for cleanup tasks like closing files, releasing database connections, or freeing other resources.

🏏

Cricket analogy: The finally block is like the mandatory post-match pitch inspection that always happens whether the game ended in a win, loss, or was abandoned for rain, used for cleanup tasks like covering the ground.

Understanding exactly when finally runs — including its interaction with return statements — is essential for writing correct resource-management code and is a frequent source of tricky exam questions.

🏏

Cricket analogy: Understanding finally's interaction with return is like knowing that even after a batsman is given out (return), the third umpire's review (finally) still runs and can affect what's officially recorded before the scoreboard updates.

2. Syntax

java
try {
    // risky code
} catch (SomeException e) {
    // handle exception
} finally {
    // cleanup code — always runs
}

3. Explanation

The finally block executes after the try block completes normally, after a catch block finishes handling an exception, or even if the try/catch block contains a return statement. Java evaluates the return value from try/catch first, but actually returns control to the caller only after finally has fully executed.

🏏

Cricket analogy: Finally executes whether the innings ends normally, after a review overturns a decision (catch), or even mid-declaration (return) — the ground staff still complete the pitch cover-up before the match is truly closed.

There are only two situations where finally does NOT run: if the JVM crashes or is forcibly terminated (e.g. via a power failure), or if the code explicitly calls System.exit() before reaching finally. Aside from these edge cases, finally is guaranteed to execute.

🏏

Cricket analogy: The only times cleanup doesn't happen are if the stadium itself collapses (JVM crash) or the match is abruptly called off by the board (System.exit()) — otherwise the ground staff always complete their post-match duties.

Exam trap: if finally itself contains a return statement, it overrides any return value from the try or catch block — this is considered poor practice and can silently swallow exceptions, but it is valid Java and a classic tricky exam question.

4. Example

java
public class FinallyDemo {
    static int test() {
        try {
            System.out.println("In try");
            return 1;
        } catch (Exception e) {
            System.out.println("In catch");
            return 2;
        } finally {
            System.out.println("In finally — cleanup runs regardless");
        }
    }

    public static void main(String[] args) {
        int result = test();
        System.out.println("Returned value: " + result);
    }
}

5. Output

text
In try
In finally  cleanup runs regardless
Returned value: 1

6. Key Takeaways

  • finally executes after try/catch completes, regardless of whether an exception occurred.
  • finally runs even when try or catch contains a return statement — it executes before control actually returns to the caller.
  • finally is typically used for cleanup: closing files, connections, or releasing other resources.
  • The only ways finally is skipped are a JVM crash or an explicit System.exit() call.
  • A return statement inside finally overrides any return value from try/catch — this is legal but bad practice.

Practice what you learned

Was this page helpful?

Topics covered

#Java#JavaProgrammingStudyNotes#Programming#FinallyBlockInJava#Finally#Block#Syntax#Explanation#StudyNotes#SkillVeris