Home » Finally Block In Java

Finally Block In Java

Finally Block In Java

Introduction

Finally block in java contains all the crucial statements that must be executed whether exception occurs or not. The statements present in this block will always execute regardless of whether exception occurs in try block or not such as closing a connection, stream etc. The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception. Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code.

Syntax

try {
   // Protected code
} catch (ExceptionType1 e1) {
   // Catch block
} catch (ExceptionType2 e2) {
   // Catch block
} catch (ExceptionType3 e3) {
   // Catch block
}finally {
   // The finally block always executes.
}
Java

Flowchart of finally block in java

Points To Remember While Using Finally Block in Java

  • A catch clause cannot exist without a try statement.
  • It is not compulsory to have finally clauses whenever a try/catch block is present.
  • The try block cannot be present without either catch clause or finally clause.
  • Any code cannot be present in between the try, catch, finally blocks.
  • finally block is not executed in case exit() method is called before finally block or a fatal error occurs in program execution.
  • finally block is executed even method returns a value before finally block.

Why Java Finally Block Used?

  • Java finally block can be used for clean-up (closing) the connections, files opened, streams, etc. those must be closed before exiting the program.
  • It can also be used to print some final information.

Example 1

public class FinallyExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0; // This will cause ArithmeticException
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: Division by zero");
        } finally {
            System.out.println("Finally block executed");
        }
    }
}
Java

Output

Error: Division by zero
Finally block executed
Java

Example 2

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

    public static int testFinally() {
        try {
            return 1;
        } catch (Exception e) {
            return 2;
        } finally {
            return 3;
        }
    }
}
Java

Output

3
Java

Example 3

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;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        } finally {
            try {
                if (reader != null)
                    reader.close();
            } catch (IOException e) {
                System.out.println("Error closing reader: " + e.getMessage());
            }
            System.out.println("Finally block executed");
        }
    }
}
Java

Output

Contents of example.txt
Finally block executed
Java

Conclusion

In conclusion, the finally block in Java is a fundamental feature used in exception handling. It provides a mechanism to execute essential code that must be run whether an exception occurs or not. Key points regarding the finally block include:

  1. Execution Guarantee: The code within the finally block is guaranteed to execute, irrespective of whether an exception is thrown or not. This ensures critical cleanup tasks or resource deallocation occurs reliably, enhancing the robustness of the program.
  2. Useful for Resource Management: finally blocks are commonly used for releasing resources such as file handles, database connections, or network sockets. This ensures that resources are properly released, preventing potential resource leaks and improving system stability.
  3. Combination with Try-Catch Blocks: finally blocks are often used in conjunction with try-catch blocks. While try-catch handles exceptions, finally ensures that cleanup operations are performed regardless of whether an exception is caught or not.
  4. Potential Pitfalls: While finally blocks offer valuable functionality, developers should be cautious of potential pitfalls, such as inadvertently masking exceptions thrown within the finally block, which can lead to unexpected behavior.

Overall, the finally block plays a crucial role in exception handling and resource management in Java, contributing to the development of robust and reliable applications.

Frequently Asked Questions

1. What is the purpose of the finally block in Java?

The finally block in Java is used to define code that must be executed regardless of whether an exception occurs in the preceding try block or not. It ensures that essential cleanup tasks are performed, such as releasing resources or closing connections, contributing to the overall robustness of the program.

2. Can a finally block be used without a try block?

No, a finally block must always be associated with a preceding try block. It cannot exist independently. The finally block provides a mechanism to define cleanup code that executes whether an exception occurs or not within the associated try block.

3. What happens if an exception is thrown from within the finally block itself?

If an exception is thrown from within the finally block, it will override any exception thrown in the preceding try block or catch block. However, the original exception will not be lost; it will still be accessible through the Throwable object thrown in the finally block.