0
0
JavaHow-ToBeginner · 3 min read

How to Use finally in Java: Syntax, Example, and Tips

In Java, the finally block is used after try and catch blocks to execute code that must run regardless of exceptions. It is commonly used for cleanup tasks like closing files or releasing resources.
📐

Syntax

The finally block follows try and optional catch blocks. It contains code that always runs after the try block finishes, whether an exception was thrown or not.

  • try: Code that might throw an exception.
  • catch: Code to handle specific exceptions.
  • finally: Code that always runs after try/catch, used for cleanup.
java
try {
    // code that may throw exception
} catch (ExceptionType e) {
    // handle exception
} finally {
    // code that always runs
}
💻

Example

This example shows how finally runs whether or not an exception occurs. It closes a resource after use.

java
public class FinallyExample {
    public static void main(String[] args) {
        try {
            System.out.println("Inside try block");
            int result = 10 / 0; // causes ArithmeticException
        } catch (ArithmeticException e) {
            System.out.println("Exception caught: " + e.getMessage());
        } finally {
            System.out.println("Finally block always runs");
        }
        System.out.println("Program continues after try-catch-finally");
    }
}
Output
Inside try block Exception caught: / by zero Finally block always runs Program continues after try-catch-finally
⚠️

Common Pitfalls

One common mistake is assuming finally runs even if the program exits abruptly, like with System.exit(). Also, if finally itself throws an exception, it can hide exceptions from try or catch. Avoid returning from finally as it can override exceptions.

java
public class FinallyPitfall {
    public static void main(String[] args) {
        try {
            System.out.println("Try block");
            return; // returning here
        } finally {
            System.out.println("Finally block still runs before return");
            // Avoid return here to not override
        }
    }
}
Output
Try block Finally block still runs before return
📊

Quick Reference

AspectDescription
PurposeRun code always after try/catch, usually for cleanup
ExecutionRuns whether exception occurs or not
Exceptions in finallyCan override exceptions from try/catch if not handled
Return in finallyAvoid as it overrides exceptions or returns from try
Use caseClosing files, releasing resources, logging

Key Takeaways

The finally block always executes after try and catch blocks, even if exceptions occur.
Use finally to clean up resources like files or database connections.
Avoid returning from finally to prevent hiding exceptions or altering program flow.
If finally throws an exception, it can override exceptions from try or catch.
Finally does not run if the JVM exits abruptly (e.g., System.exit()).