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

Wrapping Exceptions: throw new Exception(cause)

Learn to wrap caught exceptions in new exception types while preserving the original cause.

Wrapping Exceptions: throw new Exception(cause)

What You'll Learn

You'll learn how to wrap a caught exception inside a new exception type while preserving the original error's details and stack trace.


Why Wrap Exceptions?

Sometimes you catch a low-level exception (like SQLException or IOException) but want to throw a more meaningful, application-specific exception to your caller. However, you don't want to lose the original error information—that's valuable for debugging!

Wrapping lets you create a new exception that carries the original exception as its cause.

The Pattern

When catching an exception, instead of rethrowing it directly, you can create a new exception and pass the caught exception to its constructor:

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

Notice the second parameter e—this preserves the original SQLException as the cause of the new RuntimeException.

How It Works

Most exception classes provide a constructor that accepts:

  1. A custom message string
  2. A Throwable cause

The cause is stored inside the new exception. When the stack trace prints, you'll see both exceptions—the wrapper and the original cause—giving you complete diagnostic information.

Why This Matters

  • Abstraction: Your method can throw domain-specific exceptions without exposing implementation details
  • Context: Add a meaningful message while keeping technical details
  • Debugging: The full chain of exceptions helps trace problems from high-level code down to root causes

Key Takeaway:
Wrapping exceptions with throw new Exception(cause) lets you create layered, meaningful error messages while preserving the complete original stack trace for debugging.