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

  • DataAccessException extends Exception: constructor with message and cause
  • ServiceException extends Exception: constructor with message and cause
  • Repository class: findById(int id) method
    • If id < 0: throws DataAccessException("Invalid ID: " + id, new IllegalArgumentException("ID must be positive"))
  • Service class: getUser(int id) method
    • Calls Repository.findById(), catches DataAccessException and wraps in ServiceException
  • 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