Phase 13 of 20 · Topic 13.4

Custom Domain Exceptions & Exception Chaining

1Concept

Enterprise applications define domain-specific exceptions (e.g. `PaymentGatewayException`, `UserNotFoundException`). Exception Chaining wraps low-level technical errors (e.g. `SQLException`) inside high-level domain exceptions while preserving the original root cause stack trace (`new CustomException("message", cause)`).

2Architecture Diagram

[ SQLException: Connection refused (Low-Level) ]
                       |
                 Wrapped inside
                       v
[ PaymentProcessingException: Transaction Failed (High-Level Domain Error) ]

3Code Example

Core Java
public class ExceptionChainingDemo {
    static class PaymentProcessingException extends RuntimeException {
        public PaymentProcessingException(String message, Throwable cause) {
            super(message, cause); // Preserves original root cause stack trace
        }
    }

    static void processPayment() {
        try {
            throw new java.net.ConnectException("Timeout connecting to Visa Payment Gateway");
        } catch (java.net.ConnectException ce) {
            throw new PaymentProcessingException("Payment failed due to upstream network issue", ce);
        }
    }

    public static void main(String[] args) {
        try {
            processPayment();
        } catch (PaymentProcessingException e) {
            System.err.println("Domain Error: " + e.getMessage());
            System.err.println("Root Cause:   " + e.getCause().getClass().getName() + ": " + e.getCause().getMessage());
        }
    }
}

4Expected Output

Domain Error: Payment failed due to upstream network issue
Root Cause:   java.net.ConnectException: Timeout connecting to Visa Payment Gateway

5Key Takeaways

  • Always pass the original cause (`cause`) to the superclass constructor to avoid losing stack traces.
  • Use domain exceptions to decouple business logic from infrastructure failures.
  • Provide meaningful error codes or structured error attributes in custom exceptions.