Can you explain the role of each try, catch, and finally block in exception handling?

In Java exception handling, the try, catch, and finally blocks work together to detect, handle, and clean up after runtime errors. They help ensure that applications continue to run gracefully even when unexpected situations occur.

Diagram: execution flow of try, catch and finally
execution flow of try, catch and finally

Key Points

Example

When reading data from a file, the file operation is placed inside the try block, any file-related errors are handled in the catch block, and the file is closed in the finally block.

public class Demo {

    public static void main(String[] args) {

        try {
            int result = 10 / 0;
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero");
        } finally {
            System.out.println("Finally block executed");
        }
    }
}

Flow of Execution

1. try block executes first.

2. If an exception occurs, control moves to the matching catch block.

3. After try or catch execution, the finally block runs.

4. If no exception occurs, catch is skipped and finally still executes.

Common Mistakes

Follow-up Questions

Interview Tip

A concise interview answer is

The try block contains code that may generate an exception, the catch block handles the exception, and the finally block contains cleanup code that executes regardless of whether an exception occurs. This mechanism helps build robust and reliable Java applications.

Last updated: 11 November 2026

Previous question: Is there a scenario where autoboxing and unboxing could cause a NullPointerException?

Next question: What happens if a return statement is executed inside the try or catch block? Does the finally block still execute?

More Core Java - Level II interview questions

All Core Java - Level II questions