019-002-011
Exception Chaining with Cause
Hard
Problem Description
Exception Chaining with Cause
In this problem: You will implement the "exception chaining" pattern that wraps low-level exceptions in high-level exceptions while preserving the original cause for traceability.
Learning Objective: Understand exception chaining (cause) mechanism and practical usage
Overview
Exception chaining preserves the original exception as the cause when catching a low-level exception and converting it to a high-level one.
Specifications
DataAccessExceptionextendsException: constructor with message and causeServiceExceptionextendsException: constructor with message and causeRepositoryclass:findById(int id)method- If id < 0: throws
DataAccessException("Invalid ID: " + id, new IllegalArgumentException("ID must be positive"))
- If id < 0: throws
Serviceclass:getUser(int id)method- Calls
Repository.findById(), catchesDataAccessExceptionand wraps inServiceException
- Calls
- In Main, traverse the exception chain and output each level's message
Output Format
Service error: Failed to get user
Caused by: Invalid ID: -1
Root cause: ID must be positive
Ready to Try Running Code?
Log in to access the code editor and execute your solutions for this problem.
Don't have an account?
Sign Up