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

Chained Exceptions and initCause

Understand exception chaining to preserve the original cause when wrapping exceptions, and how to access the full chain.

Chained Exceptions and initCause

What You'll Learn

You'll learn how to chain exceptions together to preserve the original cause when wrapping exceptions, and how to access the complete chain of exceptions.

Why Chain Exceptions?

Sometimes you catch a low-level exception (like SQLException) but want to throw a higher-level, more meaningful exception to your caller (like DataAccessException). When you do this, you don't want to lose the original error information—it's critical for debugging.

Analogy: Think of it like a detective preserving evidence. When passing a case to a higher authority, you don't just describe the problem—you attach all the original evidence so the full story is available.

How Exception Chaining Works

You've already seen that Throwable has a getCause() method. This returns the exception that caused the current exception. You create this chain in two ways:

1. Using Exception Constructors: Many exception classes have constructors that accept a Throwable cause parameter:

try {
    // code that throws IOException
} catch (IOException e) {
    throw new RuntimeException("Failed to process file", e);
}

2. Using initCause() Method: If an exception doesn't have a constructor with a cause parameter, use initCause():

MyException ex = new MyException("Something went wrong");
ex.initCause(originalException);
throw ex;

Accessing the Chain

Use getCause() to walk through the chain:

Throwable cause = exception.getCause();
while (cause != null) {
    // examine cause
    cause = cause.getCause();
}

The printStackTrace() method automatically shows the entire chain.

Key Takeaway: Exception chaining with initCause() or cause-accepting constructors preserves the complete error history, making debugging easier by maintaining the full context of what went wrong.