Course contentsShow
← Java
Lesson 819 of 2,87019. Exception Hierarchy and Custom ExceptionsFree lesson

Exception Hierarchies for Related Errors

Build exception hierarchies with base custom exceptions and specific subclasses for granular error handling.

Exception Hierarchies for Related Errors

What You'll Learn

You'll learn how to build exception hierarchies with a base custom exception and specific subclasses for granular error handling.

Why Create Exception Hierarchies?

When building larger applications, you often encounter groups of related errors. Rather than creating dozens of independent custom exceptions, you can organize them into a hierarchy—a family tree of exceptions with a common ancestor.

Think of it like a restaurant menu: you might have a base "MenuException" for all menu-related problems, then specific subclasses like "ItemOutOfStockException" or "InvalidIngredientException." This lets callers catch either the specific error or handle all menu problems with one catch block.

Building an Exception Hierarchy

Start with a base exception that represents the broad category:

public class PaymentException extends Exception {
    public PaymentException(String message) {
        super(message);
    }
    
    public PaymentException(String message, Throwable cause) {
        super(message, cause);
    }
}

Then create specific subclasses for particular error cases:

public class InsufficientFundsException extends PaymentException {
    public InsufficientFundsException(String message) {
        super(message);
    }
}

public class InvalidCardException extends PaymentException {
    public InvalidCardException(String message) {
        super(message);
    }
}

public class PaymentTimeoutException extends PaymentException {
    public PaymentTimeoutException(String message) {
        super(message);
    }
}

Using Your Exception Hierarchy

Now you can catch granularly or broadly:

try {
    processPayment();
} catch (InsufficientFundsException e) {
    // Handle specifically
} catch (PaymentException e) {
    // Handle all other payment errors
}

Key Takeaway: Exception hierarchies organize related errors into inheritance trees, enabling both specific handling for precise cases and general handling for entire error categories through polymorphism.