0
0
Javaprogramming~5 mins

Finally block in Java

Choose your learning style9 modes available
Introduction

The finally block is used to run code that must happen no matter what, like cleaning up or closing resources.

You want to close a file or database connection after using it.
You need to release resources even if an error happens.
You want to print a message that always shows after a try-catch.
You want to reset some settings regardless of success or failure.
Syntax
Java
try {
    // code that might throw an exception
} catch (ExceptionType name) {
    // code to handle the exception
} finally {
    // code that always runs
}

The finally block runs after try and catch, no matter what.

If there is a return statement in try or catch, finally still runs before returning.

Examples
This example catches a divide-by-zero error and always prints the final message.
Java
try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero.");
} finally {
    System.out.println("This always runs.");
}
Here, there is no catch, but the finally block still runs after try.
Java
try {
    System.out.println("Try block running.");
} finally {
    System.out.println("Finally block running.");
}
Sample Program

This program tries to divide by zero, catches the error, and then runs the finally block. The program then continues normally.

Java
public class FinallyExample {
    public static void main(String[] args) {
        try {
            System.out.println("Inside try block.");
            int division = 10 / 0; // This will cause an exception
        } catch (ArithmeticException e) {
            System.out.println("Caught an ArithmeticException.");
        } finally {
            System.out.println("Finally block always executes.");
        }
        System.out.println("Program continues after try-catch-finally.");
    }
}
OutputSuccess
Important Notes

The finally block is useful for cleanup like closing files or releasing resources.

If the JVM exits (like calling System.exit()), the finally block may not run.

Use finally to make sure important code runs no matter what.

Summary

The finally block runs always after try and catch blocks.

It is used to clean up or finalize actions.

Even if an exception happens or a return statement is used, finally still runs.