100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Java

try-catch in Java

Learn how to use try, catch, multi-catch, and try-with-resources blocks in Java to handle exceptions cleanly.

Exception HandlingBeginner9 min readJul 7, 2026
Analogies

1. Introduction

The try-catch construct is the core mechanism Java provides for handling exceptions. Code that might throw an exception is placed inside a try block, and code that handles a specific exception type is placed inside one or more catch blocks that follow it.

🏏

Cricket analogy: The try block is like a batsman facing a risky yorker; the catch block is the specific plan, say a defensive block, prepared in advance for exactly that kind of delivery.

Java also supports multiple catch blocks for handling different exception types differently, a multi-catch syntax for combining handlers, and try-with-resources for automatically closing resources like files and database connections.

🏏

Cricket analogy: A captain plans separate responses for a rain delay versus a bad-light stoppage (multiple catch blocks), a combined response for either minor stoppage (multi-catch), and an auto-covering-of-the-pitch system that activates without manual action (try-with-resources).

2. Syntax

java
try {
    // risky code
} catch (SpecificException e) {
    // handle specific exception
} catch (MoreGeneralException e) {
    // handle more general exception
}

// Multi-catch
try {
    // risky code
} catch (IOException | SQLException e) {
    // handle either type
}

// try-with-resources
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    // use br
} catch (IOException e) {
    // handle exception
}

3. Explanation

When an exception occurs inside a try block, Java looks for the first catch block whose exception type matches (or is a superclass of) the thrown exception, executes it, and skips the rest of the try block. You can chain multiple catch blocks to handle different exception types with different logic — order matters here.

🏏

Cricket analogy: Java checks catch blocks top-down like an umpire checking the most specific rule first, a no-ball, before a general rule like illegal delivery; once the first matching rule applies, the rest of the over's other checks are skipped.

Java 7 introduced multi-catch (catch (TypeA | TypeB e)) to avoid duplicating identical handling code for unrelated exception types, and try-with-resources, which automatically closes any resource implementing AutoCloseable once the try block finishes, without needing an explicit finally block.

🏏

Cricket analogy: Multi-catch is like a single response plan covering both a "wide" and a "no-ball" without writing duplicate rules for each, and try-with-resources is like the ground staff automatically rolling up the covers once play ends, without a groundskeeper needing to remember.

Exam trap: catch blocks must be ordered from most specific to most general. If you catch a broader exception type (like Exception) before a narrower one (like ArithmeticException), the code will not compile — Java flags the narrower catch as unreachable.

4. Example

java
public class TryCatchDemo {
    public static void main(String[] args) {
        int[] data = {1, 2, 3};
        try {
            int result = 10 / 0;
            System.out.println(data[5]);
        } catch (ArithmeticException e) {
            System.out.println("Arithmetic error: " + e.getMessage());
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index error: " + e.getMessage());
        } catch (Exception e) {
            System.out.println("General error: " + e.getMessage());
        }
        System.out.println("Execution continues after handling.");
    }
}

5. Output

text
Arithmetic error: / by zero
Execution continues after handling.

6. Key Takeaways

  • try encloses risky code; catch handles a specific exception type thrown from that try block.
  • Multiple catch blocks must be ordered from most specific to most general, or the code fails to compile.
  • Multi-catch syntax catch (TypeA | TypeB e) lets one block handle multiple unrelated exception types.
  • try-with-resources automatically closes AutoCloseable resources without needing an explicit finally block.
  • Only the first matching catch block executes; the rest are skipped.

Practice what you learned

Was this page helpful?

Topics covered

#Java#JavaProgrammingStudyNotes#Programming#TryCatchInJava#Try#Catch#Syntax#Explanation#ErrorHandling#StudyNotes#SkillVeris