Java Reference Library →

finally Keyword Usage and Examples

finally Keyword Usage and Examples

Learn about the Java finally keyword, its role in exception handling, when it executes, and how it guarantees cleanup. Understand with beginner-friendly examples and detailed output explanations.

This reference explains finally Keyword Usage and Examples through its syntax, examples and boundaries. Use the linked course lessons when the surrounding Java concepts are unfamiliar.

  1. Use this reference

    Identify the documented behavior, read a complete example and check its inputs before applying it.

finally Keyword in Java

The finally keyword in Java is a block used in exception handling that guarantees the execution of code regardless of whether an exception was thrown or caught. It's most commonly used to release resources such as closing files, database connections, or network sockets.

Why Use the finally Block?

Imagine you're opening a file or a database connection. Whether your program succeeds or fails, you must ensure the resource is released properly. That’s where finally comes in — it runs no matter what.

Syntax of try-catch-finally

try {
    // Code that may throw an exception
} catch (ExceptionType e) {
    // Exception handling
} finally {
    // Code that will always execute
}

Example 1: Basic try-catch-finally Structure

public class FinallyExample {
    public static void main(String[] args) {
        try {
            System.out.println("Inside try block");
            int result = 10 / 2;
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Catch block: " + e.getMessage());
        } finally {
            System.out.println("Finally block always runs");
        }
    }
}
Inside try block
Result: 5
Finally block always runs

Explanation

Java · example discussed here

public class FinallyExample {
    public static void main(String[] args) {
        try {
            System.out.println("Inside try block");
            int result = 10 / 2;
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Catch block: " + e.getMessage());
        } finally {
            System.out.println("Finally block always runs");
        }
    }
}

Since no exception is thrown, the catch block is skipped. But the finally block runs anyway.

Example 2: When Exception Is Thrown

public class FinallyExample {
    public static void main(String[] args) {
        try {
            System.out.println("Inside try block");
            int result = 10 / 0; // Throws ArithmeticException
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Catch block: " + e.getMessage());
        } finally {
            System.out.println("Finally block always runs");
        }
    }
}
Inside try block
Catch block: / by zero
Finally block always runs

Even When No Catch Block Exists

The finally block can be used with try even if catch is absent. This is useful when you don't want to handle exceptions but still need cleanup.

public class FinallyOnlyExample {
    public static void main(String[] args) {
        try {
            System.out.println("Trying risky operation...");
            int result = 10 / 0;
        } finally {
            System.out.println("Cleanup happens here.");
        }
    }
}
Trying risky operation...
Cleanup happens here.
Exception in thread "main" java.lang.ArithmeticException: / by zero

Even When return Is Called

What if we return from inside a try? Will finally still run? Absolutely yes.

public class ReturnWithFinally {
    public static void main(String[] args) {
        System.out.println(testReturn());
    }

    static String testReturn() {
        try {
            return "Returning from try";
        } finally {
            System.out.println("Finally still executes before return");
        }
    }
}
Finally still executes before return
Returning from try

Key Points to Remember

  • finally always runs, whether or not an exception is thrown or caught.
  • It runs even if there is a return statement in the try or catch block.
  • Use it for cleanup operations like closing file streams or network connections.
  • Even when an exception is unhandled and the program crashes, the finally block still executes.

Use Case: Closing a File

import java.io.*;

public class FileHandling {
    public static void main(String[] args) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("file.txt"));
            System.out.println("First line: " + reader.readLine());
        } catch (IOException e) {
            System.out.println("Something went wrong: " + e.getMessage());
        } finally {
            try {
                if (reader != null) reader.close();
                System.out.println("Reader closed in finally block");
            } catch (IOException ex) {
                System.out.println("Failed to close reader");
            }
        }
    }
}

Using this reference

Check the example’s types, inputs and documented behavior before copying it into an application. Some APIs require external libraries, files or platform services; consult their setup notes.

Related explanations: Java Data Types - Primitive and Non-Primitive, Java Class - Blueprint of Objects, Exceptions in Java Introduction.

Supporting documentation: Official Java learning guide.

Reference checks are optional and do not count toward course progress.

    Reference library →