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

Exception Chaining with initCause and Constructors

Master exception chaining by passing caught exceptions as causes to maintain full error context.

Exception Chaining with initCause and Constructors

What you'll learn: How to link exceptions together to preserve the full story of what went wrong in your application.

Why Exception Chaining Matters

When you wrap one exception inside another (as you learned in the previous lesson), you want to preserve the original cause of the problem. Exception chaining formally links the caught exception to the newly thrown one, ensuring that when someone examines the error later, they can trace back through the entire chain of events.

Two Ways to Chain Exceptions

Using Exception Constructors

Most exception classes provide constructors that accept a Throwable cause parameter:

try {
    // code that throws IOException
} catch (IOException e) {
    throw new RuntimeException("Database connection failed", e);
}

The second parameter e becomes the cause of the new RuntimeException. The full context is preserved automatically.

Using initCause()

For exceptions that don't have a cause-accepting constructor, or when you need more control, use initCause():

try {
    // code that throws some exception
} catch (Exception e) {
    RuntimeException wrapper = new RuntimeException("Operation failed");
    wrapper.initCause(e);
    throw wrapper;
}

The initCause() method links the original exception to your new one. Important: You can only call initCause() once per exception object.

The Benefit

When the exception propagates up the call stack, the stack trace will show both your high-level message and the original low-level cause, giving developers the complete picture for debugging.

Key Takeaway: Exception chaining via constructor parameters or initCause() preserves the original cause, maintaining full error context as exceptions propagate through your application.