Skip to content

Finally in Java

The finally block in Java is used to ensure that a specific block of code is executed after a try and catch block, regardless of whether an exception was thrown or not. It is part of the exception handling mechanism and is often used for code that must execute no matter what, such as releasing resources, closing connections, or cleaning up operations.


Syntax of Finally Block

try {

    // Code that may throw an exception

} catch (ExceptionType e) {

    // Code to handle the exception

} finally {

    // Code that will always be executed, regardless of an exception

}

  • The finally block is optional, but if it is used, it must come after all catch blocks.
  • It is guaranteed to execute even if no exception occurs, or if an exception is thrown and caught.
  • If a try block contains a return statement, the finally block will still be executed before the method returns.

Key Characteristics of Finally Block

  1. Execution Guarantee:
    1. The finally block runs no matter what happens in the try or catch blocks, including whether an exception is thrown or not.
  2. Resource Management:
    1. It is commonly used to close resources like files, database connections, or network sockets.
  3. Cannot Be Skipped:
    1. Even if a return statement or an System.exit() call is made in the try or catch block, the finally block will still be executed (unless the JVM itself shuts down).
  4. Can Be Omitted:
    1. A finally block is optional, so if you don’t need to perform cleanup actions, you can exclude it.

Example of Finally Block

public class FinallyExample {

    public static void main(String[] args) {

        try {

            int result = 10 / 0; // This will throw an ArithmeticException

        } catch (ArithmeticException e) {

            System.out.println(“Caught an ArithmeticException: Division by zero.”);

        } finally {

            System.out.println(“This block will always execute.”);

        }

        System.out.println(“Program continues after the finally block.”);

    }

}

Output:

Caught an ArithmeticException: Division by zero.

This block will always execute.

Program continues after the finally block.


Example with Resource Management

import java.io.FileWriter;

import java.io.IOException;

public class FinallyExample2 {

    public static void main(String[] args) {

        FileWriter writer = null;

        try {

            writer = new FileWriter(“example.txt”);

            writer.write(“Hello, world!”);

        } catch (IOException e) {

            System.out.println(“An IOException occurred: ” + e.getMessage());

        } finally {

            try {

                if (writer != null) {

                    writer.close();

                    System.out.println(“FileWriter closed.”);

                }

            } catch (IOException e) {

                System.out.println(“Failed to close FileWriter: ” + e.getMessage());

            }

        }

    }

}

Explanation:

  • The finally block ensures that the FileWriter is closed regardless of whether an exception occurred in the try block.
  • This is crucial for resource management and avoiding memory leaks.

Behavior with Return Statements

When a return statement is present in the try or catch block, the finally block is still executed before the method completes.

Example

public class FinallyReturnExample {

    public static void main(String[] args) {

        System.out.println(testMethod());

    }

    public static String testMethod() {

        try {

            return “From try block”;

        } catch (Exception e) {

            return “From catch block”;

        } finally {

            System.out.println(“Finally block executed.”);

        }

    }

}

Output:

Finally block executed.

From try block

Explanation:

  • The finally block runs before the method returns, even when the try block has a return statement.

Interaction with Exception Propagation

If an exception is thrown in the try block and caught in a catch block, the finally block will still execute after the catch block.

Example

public class FinallyExceptionExample {

    public static void main(String[] args) {

        try {

            int[] arr = new int[3];

            arr[5] = 10; // ArrayIndexOutOfBoundsException

        } catch (ArrayIndexOutOfBoundsException e) {

            System.out.println(“Caught an ArrayIndexOutOfBoundsException.”);

        } finally {

            System.out.println(“Finally block executed.”);

        }

    }

}

Output:

Caught an ArrayIndexOutOfBoundsException.

Finally block executed.


Conclusion

The finally block in Java is a powerful feature that ensures certain code is always executed, regardless of whether an exception occurred or not. This is particularly useful for releasing resources and performing cleanup tasks, ensuring that the program remains stable and efficient. While it is optional, using finally appropriately helps make applications more reliable and maintainable.