Course contentsShow
← Java
Lesson 758 of 2,87018. Exception Handling FundamentalsFree lesson

Catch Block Order: Most Specific First

Why catch blocks must be ordered from most specific to most general exception types.

Catch Block Order: Most Specific First

What you'll learn: Why the compiler enforces ordering rules when you write multiple catch blocks.

When you have multiple catch blocks handling different exception types, Java requires you to order them from most specific to most general. This means child exception classes must appear before their parent classes.

Why This Rule Exists

Think of catching exceptions like filtering water through a series of increasingly coarse sieves. If you put the coarsest sieve (most general exception) first, it catches everything, and the finer sieves below never get a chance to work.

Java processes catch blocks from top to bottom. The first block that matches the thrown exception's type will execute. If you put a general exception type (like Exception) before a specific one (like ArithmeticException), the general catch would always match first—making the specific catch unreachable code.

The Compiler Enforces This

try {
    int result = 10 / 0;
} catch (Exception e) {           // Too general!
    System.out.println("General");
} catch (ArithmeticException e) {  // COMPILE ERROR: unreachable
    System.out.println("Specific");
}

This code won't compile. Since ArithmeticException is a subclass of Exception, the first catch block would always handle it.

The Correct Order

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {  // Most specific first
    System.out.println("Arithmetic problem");
} catch (Exception e) {            // Most general last
    System.out.println("Other problem");
}

Now each catch block can actually be reached based on the thrown exception type.

Key Takeaway: Always order catch blocks from most specific exception type to most general—the compiler prevents unreachable catch blocks by enforcing this rule.