Exception Chaining in Java: Explanation & Practice

Chain exceptions to preserve root cause

Problem summary

Create a ServiceException that wraps lower-level exceptions while preserving the original cause.

Starter code

class ServiceException extends Exception {
    // Constructor that accepts message and cause
}

class DataException extends Exception {
    public DataException(String msg) { super(msg); }
}

public class Main {
    static void fetchData() throws DataException {
        throw new DataException("Database connection failed");
    }
    
    static void processRequest() throws ServiceException {
        try {
            fetchData();
        } catch (DataException e) {
            // Wrap in ServiceException
            throw new ServiceException("Service failed", e);
        }
    }
    
    public static void main(String[] args) {
        try {
            processRequest();
        } catch (ServiceException e) {
            System.out.println("Caught: " + e.getMessage());
            System.out.println("Cause: " + e.getCause().getMessage());
        }
    }
}

Expected output and test cases

  • Exception chain preserved
    Caught: Service failed
    Cause: Database connection failed

Hints

  1. Use super(message, cause) constructor
  2. getCause() returns the wrapped exception
  3. Helps trace root cause of errors

Related Exception Handling exercises

Practice all Exception Handling exercises · Run this idea in the Java compiler