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:
- A custom message string
- A
Throwablecause
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.