Exception Chaining in Java: Example, Cause and Practice
Chain exceptions to preserve cause
Problem summary
Catch a low-level exception and wrap it in a higher-level exception.
Starter code
// Create DataProcessingException
// Wrap NumberFormatException as cause
public class Main {
public static void main(String[] args) {
String data = "not a number"; // Test case 1
// Process data, chain exceptions
}
}Expected output and test cases
- Chained exception
Processing failed: Data parsing error Cause: For input string: "not a number"
- Valid data
Processing succeeded: 42
- Null input
Processing failed: Data parsing error Cause: null
Hints
- new HighLevelException(message, cause)
- getCause() retrieves wrapped exception
- Preserves stack trace information
How to approach the problem
Catch the low-level exception and pass it as the cause when constructing the higher-level exception. Call getCause() when diagnostic code needs to inspect the original failure.
Common mistakes
- Creating a new exception without passing the original cause.
- Printing only the wrapper message and discarding the original stack trace.
- Using exception chaining for normal control flow instead of genuine failures.
Related Exception Handling exercises
- Practice Custom Exception Class in Java
- Practice Input Validation with Exceptions in Java
- Practice Retry with Exceptions in Java
Practice all Exception Handling exercises · Run this idea in the Java compiler