Java Programming Handbook

    Finally Block in Java

    Introduction#

    Exception handling in Java provides several constructs like try, catch, throw, and throws. However, in many cases, we need to ensure that some code executes regardless of whether an exception occurs or not. This is where the finally block comes into play.

    In this blog, we will cover:

    • What is the finally block?
    • Why is it needed?
    • How does it work with try-catch?
    • Practical examples
    • Best practices

    What is the finally Block?#

    The finally block in Java is used to execute important code after the try-catch block. It runs regardless of whether an exception is thrown or caught, making it useful for resource cleanup like closing database connections, file streams, or network sockets.

    Key Features:#

    • The finally block is optional but highly recommended.
    • It always executes, even if an exception is not thrown.
    • It runs even if there is a return statement inside the try or catch block.

    Syntax of finally Block#

    try { // Code that may throw an exception } catch (ExceptionType e) { // Handle exception } finally { // Cleanup code that always executes }

    Example: Using finally with Exception Handling#

    public class FinallyExample { public static void main(String[] args) { try { int result = 10 / 0; // This will cause an exception } catch (ArithmeticException e) { System.out.println("Exception caught: " + e.getMessage()); } finally { System.out.println("Finally block executed"); } } }

    Output:#

    Exception caught: / by zero Finally block executed

    Explanation: The finally block executes after handling the ArithmeticException, ensuring that the necessary cleanup operations are performed.

    Example: finally Without an Exception#

    public class FinallyNoException { public static void main(String[] args) { try { System.out.println("Try block executed"); } catch (Exception e) { System.out.println("Exception caught"); } finally { System.out.println("Finally block executed"); } } }

    Output:#

    Try block executed Finally block executed

    Explanation: Since no exception is thrown, the catch block is skipped, but the finally block still executes.

    Example: finally with return Statement#

    Even if a return statement is present in the try block, the finally block still executes before the method exits.

    public class FinallyWithReturn { public static int getNumber() { try { return 10; } finally { System.out.println("Finally block executed before returning"); } } public static void main(String[] args) { System.out.println("Returned value: " + getNumber()); } }

    Output:#

    Finally block executed before returning Returned value: 10

    Explanation: Even though return 10; is inside the try block, the finally block executes before the return statement takes effect.

    When Does the finally Block NOT Execute?#

    The finally block will not execute in the following cases:

    1. If the JVM terminates the program using System.exit(0);
    2. If a fatal error occurs (like StackOverflowError or OutOfMemoryError)

    Example:#

    public class FinallyNotExecuted { public static void main(String[] args) { try { System.out.println("Inside try block"); System.exit(0); // Terminates JVM } finally { System.out.println("Finally block (won't execute)"); } } }

    Output:#

    Inside try block

    Explanation: Since System.exit(0); terminates the JVM, the finally block does not get a chance to execute.

    Best Practices for Using finally#

    • Always use finally when working with external resources (files, databases, network connections) to ensure proper cleanup.
    • Avoid placing return statements inside finally, as it can override the return value of the method.
    • Be cautious while using System.exit(0); as it prevents the finally block from executing.
    • Don’t include complex logic in finally; keep it simple for cleanup purposes.

    Conclusion#

    In this blog, we learned:

    • The purpose and usage of the finally block in Java.
    • How it ensures cleanup actions after exception handling.
    • Various scenarios where finally is executed (or not executed).
    • Best practices to follow when using finally.

    Next, we will explore Try-with-Resources in Java, which is another powerful way to handle resource management efficiently.

    Last updated on Apr 09, 2025