AlgoInsight

Q&A

"Try, catch, and finally" block in Java

By AlgoInsight Team2026-06-07java

Overview

Exceptions are events that disrupt normal flow (bad input, missing file, network failure). Rather than crashing, Java lets you handle them. try wraps risky code; catch reacts to specific failures; finally guarantees cleanup. Proper exception handling is essential for robust programs.

graph TD
    A[try block runs] --> B{Exception thrown?}
    B -->|no| C[skip catch]
    B -->|yes| D[matching catch handles it]
    C --> E[finally runs ALWAYS]
    D --> E
    E --> F[continue / propagate]
    style E fill:#1e1b4b,color:#fff

Basic Structure

try {
    int result = 10 / divisor;        // might throw ArithmeticException
    System.out.println(result);
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero: " + e.getMessage());
} finally {
    System.out.println("This always runs.");
}

Multiple catch Blocks

Order matters - list more specific exceptions before their superclasses:

try {
    process(input);
} catch (FileNotFoundException e) {     // specific first
    log("File missing");
} catch (IOException e) {                 // broader after
    log("I/O problem");
} catch (Exception e) {                   // most general last
    log("Unexpected error");
}

A more specific type listed after a broader one is a compile error (unreachable).

Multi-catch (one handler, several types)

try {
    risky();
} catch (IOException | SQLException e) {   // handle both the same way
    log("Operation failed: " + e.getMessage());
}

Why finally Matters

finally runs even if the try or catch executes a return, throws, or breaks - so it's the reliable place to release resources:

Connection conn = openConnection();
try {
    conn.query("...");
    return result;            // finally STILL runs before returning
} catch (SQLException e) {
    handle(e);
} finally {
    conn.close();             // guaranteed cleanup
}

The only things that skip finally are JVM exit (System.exit) or a hard crash.

Try-with-Resources (modern, preferred)

For anything implementing AutoCloseable, declare it in the try(...) header and Java closes it automatically - no manual finally:

try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
    return br.readLine();
} catch (IOException e) {
    log("Read failed");
}
// br is closed automatically, even on exception

This is cleaner and avoids the classic bug of forgetting to close, or of a finally that itself throws. Multiple resources are closed in reverse order of declaration.

Checked vs Unchecked Exceptions

Why This Matters in Interviews

Java interviews routinely cover this. Essentials: the roles of each block, that finally always runs (even with a return in try), correct catch ordering (specific before general), multi-catch syntax, and - importantly - try-with-resources as the modern way to manage AutoCloseable resources. The checked-vs-unchecked distinction is a frequent follow-up. A subtle gotcha worth mentioning: a return in finally overrides a return in try (and is considered bad practice).

Common Pitfalls

References

More answers