Finally Block in Java: Examples, Rules and Common Mistakes

Execute cleanup code with finally

Problem summary

Demonstrate that finally block always executes, even after exception.

Starter code

public class Main {
    public static void main(String[] args) {
        // Try block that throws exception
        // Finally block prints "Cleanup complete"
    }
}

Expected output and test cases

  • Finally always runs
    Error occurred
    Cleanup complete

Hints

  1. Finally runs whether exception occurs or not
  2. Used for cleanup operations
  3. Runs even if there's a return in try/catch

How to approach the problem

A finally block normally runs after try and catch, including when either branch returns. It is intended for cleanup, but try-with-resources is safer for AutoCloseable resources. A forced JVM exit or abrupt process termination can prevent finally from running.

Common mistakes

  • Returning from finally, which can hide a return value or exception from try or catch.
  • Throwing a new exception from finally and masking the original failure.
  • Using finally for resources that should be managed by try-with-resources.

Related Exception Handling exercises

Practice all Exception Handling exercises · Run this idea in the Java compiler