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

Compiler Error: Unreachable catch Block

What happens when a more general exception is caught before a more specific one.

Compiler Error: Unreachable catch Block

What You'll Learn

You'll learn why Java prevents you from catching a more specific exception after a more general one, and how the compiler enforces this rule.

The Problem with Catching General Exceptions First

When you write multiple catch blocks, Java evaluates them in order from top to bottom. The first matching catch block handles the exception, and the rest are skipped.

If you catch a general exception (like Exception) before a more specific one (like IOException), the specific catch block will never execute—it's unreachable. Since IOException is an Exception, any IOException will always match the general Exception catch first.

Think of It Like a Net System

Imagine you're fishing with stacked nets:

  • A fine-mesh net (specific exception) catches small fish
  • A large-mesh net (general exception) catches everything

If you place the large net first, it catches all fish—including the small ones. The fine net below never gets anything. It's pointless to have it there.

The Compiler Catches This Mistake

Java's compiler detects unreachable catch blocks at compile time and issues an error. This prevents you from writing logically impossible exception handling code.

The rule: Always order catch blocks from most specific to most general. Subclass exceptions must come before their superclass exceptions.

// WRONG - Compiler error!
try {
    // code that may throw IOException
} catch (Exception e) {       // Too general, catches everything
    // handles all exceptions
} catch (IOException e) {      // ERROR: Unreachable!
    // This will NEVER execute
}

Key Takeaway: Java requires catch blocks to be ordered from most specific to most general exception types; catching a superclass exception before a subclass exception creates an unreachable catch block that the compiler rejects.