Home » Java finally block

Java finally block

In Java, the finally block is used in exception handling to ensure that a section of code is always executed, regardless of whether an exception is thrown or not.

The finally block is typically used to perform cleanup operations, like closing files, releasing resources, or closing database connections.

Syntax

The syntax for a try-catch-finally block is:

try {
    // Code that may throw an exception
} catch (ExceptionType e) {
    // Code to handle the exception
} finally {
    // Code that will always execute, regardless of an exception
}

The finally block is optional and can be used in any try-catch statement.

Even if an exception occurs and is handled (or not), the finally block will execute after the try and catch blocks.

1. Basic Example of the finally Block

In this example, we’ll see how a finally block is executed after a try block, even if no exception occurs.

public class FinallyExample {
    public static void main(String[] args) {
        try {
            System.out.println("Inside try block.");
        } catch (Exception e) {
            System.out.println("Inside catch block.");
        } finally {
            System.out.println("Inside finally block.");
        }
    }
}

Output

Inside try block.
Inside finally block.

Explanation

  • Since no exception is thrown in the try block, the catch block is skipped.
  • The finally block is executed immediately after the try block, displaying “Inside finally block”.

2. finally Block with an Exception Thrown

Here’s an example where an exception is thrown, but the finally block still executes after handling the exception.

public class FinallyWithException {
    public static void main(String[] args) {
        try {
            System.out.println("Inside try block.");
            int result = 10 / 0; // This will throw ArithmeticException
        } catch (ArithmeticException e) {
            System.out.println("Exception caught: " + e);
        } finally {
            System.out.println("Inside finally block.");
        }
    }
}

Output

Inside try block.
Exception caught: java.lang.ArithmeticException: / by zero
Inside finally block.

Explanation

  • The try block throws an ArithmeticException due to division by zero.
  • The catch block catches the exception and prints a message.
  • The finally block is executed after the catch block, ensuring cleanup actions are always performed.

3. finally Block with System Exit

If you call System.exit() in a try or catch block, the finally block will not execute, as System.exit() terminates the program immediately.

public class FinallyWithExit {
    public static void main(String[] args) {
        try {
            System.out.println("Inside try block.");
            System.exit(0); // Exit the program
        } catch (Exception e) {
            System.out.println("Inside catch block.");
        } finally {
            System.out.println("Inside finally block."); // This will NOT execute
        }
    }
}

Output

Inside try block.

Explanation

  • System.exit(0); is called within the try block, causing the program to terminate immediately.
  • The finally block does not execute because the program has already exited.

4. Using finally for Resource Cleanup

The finally block is commonly used for closing resources like files, network connections, or database connections. This example shows how to use the finally block to ensure a file is closed after reading.

import java.io.*;

public class FinallyResourceCleanup {
    public static void main(String[] args) {
        BufferedReader reader = null;
        
        try {
            reader = new BufferedReader(new FileReader("example.txt"));
            String line = reader.readLine();
            System.out.println("First line of the file: " + line);
        } catch (IOException e) {
            System.out.println("An I/O error occurred: " + e.getMessage());
        } finally {
            try {
                if (reader != null) {
                    reader.close(); // Ensure the file is closed
                    System.out.println("File closed successfully.");
                }
            } catch (IOException e) {
                System.out.println("Failed to close the file.");
            }
        }
    }
}

Explanation

  • BufferedReader is used to read from a file named “example.txt”.
  • In the finally block, reader.close() is called to ensure the file is closed even if an exception occurs.
  • The finally block ensures that the resource (file) is always cleaned up.

5. Nested try-catch-finally Blocks

In Java, you can nest try-catch-finally blocks. In this example, an inner try-catch-finally block is placed inside an outer try-catch-finally.

public class NestedFinallyExample {
    public static void main(String[] args) {
        try {
            System.out.println("Outer try block.");
            try {
                System.out.println("Inner try block.");
                int result = 10 / 0; // This will throw ArithmeticException
            } catch (ArithmeticException e) {
                System.out.println("Inner catch block: " + e);
            } finally {
                System.out.println("Inner finally block.");
            }
        } catch (Exception e) {
            System.out.println("Outer catch block.");
        } finally {
            System.out.println("Outer finally block.");
        }
    }
}

Output

Outer try block.
Inner try block.
Inner catch block: java.lang.ArithmeticException: / by zero
Inner finally block.
Outer finally block.

Explanation

  • Both finally blocks are executed, ensuring cleanup for both inner and outer blocks.
  • The ArithmeticException in the inner try block is caught by the inner catch block.
  • Both the inner and outer finally blocks execute, demonstrating that each block maintains its own finally section.

6. finally Block with Multiple Exceptions

This example demonstrates how finally behaves with multiple exceptions.

public class FinallyWithMultipleExceptions {
    public static void main(String[] args) {
        try {
            int[] arr = new int[2];
            System.out.println("First element: " + arr[0]);
            System.out.println("Accessing out-of-bounds element: " + arr[3]); // ArrayIndexOutOfBoundsException
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index out of bounds: " + e);
        } catch (Exception e) {
            System.out.println("General exception: " + e);
        } finally {
            System.out.println("Inside finally block.");
        }
    }
}

Output

First element: 0
Array index out of bounds: java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 2
Inside finally block.

Explanation

  • The try block throws an ArrayIndexOutOfBoundsException.
  • The catch block for ArrayIndexOutOfBoundsException handles this specific exception.
  • The finally block executes afterward, regardless of whether the exception is handled.

7. finally Block in a Method with a Return Statement

Even if a try or catch block has a return statement, the finally block will still execute before returning the value.

public class FinallyWithReturn {
    public static int testMethod() {
        try {
            System.out.println("Inside try block.");
            return 1;
        } catch (Exception e) {
            System.out.println("Inside catch block.");
            return 2;
        } finally {
            System.out.println("Inside finally block.");
        }
    }

    public static void main(String[] args) {
        int result = testMethod();
        System.out.println("Returned value: " + result);
    }
}

Output

Inside try block.
Inside finally block.
Returned value: 1

Explanation

  • testMethod() has a return statement in the try block.
  • Even though return 1 is executed, the finally block still executes before the method returns the value.
  • This behavior ensures that cleanup operations in finally are always performed.

Summary

The finally block is an essential feature in Java for resource management and cleanup.

It ensures that a specific block of code executes after try and catch blocks, regardless of exceptions.

Use Cases:

  • Closing files or database connections.
  • Releasing resources.
  • Ensuring important actions occur even if an exception is thrown.

Key Points:

  • The finally block always executes after try and catch blocks.
  • System.exit() will prevent the finally block from executing.
  • finally is still executed even if there’s a return in try or catch

You may also like