Can we write multiple finally blocks in Java?

No, Java does not allow multiple finally blocks for a single try-catch structure. Each try block can be associated with only one finally block, which is executed after the try and catch blocks complete.

Key Points: • A try block can have multiple catch blocks but only one finally block. • The finally block is used to execute cleanup code regardless of whether an exception occurs. • Attempting to add more than one finally block to the same try statement results in a compilation error. • If multiple cleanup operations are required, they can be placed inside a single finally block. • Nested try-catch-finally structures can be used when different cleanup logic is needed at different levels.

Example: A program may close a file, release a database connection, and clean up network resources within the same finally block.

Code Example:

public class Demo {

    public static void main(String[] args) {

        try {
            System.out.println("Inside try");
        } catch (Exception e) {
            System.out.println("Inside catch");
        } finally {
            System.out.println("Cleanup operation 1");
            System.out.println("Cleanup operation 2");
        }
    }
}

Interview Tip: A concise interview answer is:

"No, a single try-catch structure can have only one finally block. If multiple cleanup tasks are needed, they should be placed within that single finally block or handled using nested try-catch-finally structures."