019-006-010

Custom Exception Hierarchy Design

Hard

Problem Description

Custom Exception Hierarchy Design

In this problem: You will design ValidationException and NotFoundException extending a base class AppException, create a UserService class that throws different exceptions based on conditions, and handle them in Main with multi-level catch blocks.

Learning Objective: Understand custom exception hierarchy design and selective exception handling with multi-level catch

Overview

In real-world applications, custom exception hierarchies are designed to distinguish between error types. Using specific exception classes derived from a base exception class, catch blocks can perform different processing for each type.

Specifications

  • AppException (extends Exception): Has a constructor that accepts a message
  • ValidationException (extends AppException): Has a constructor that accepts a message
  • NotFoundException (extends AppException): Has a constructor that accepts a message
  • UserService class
    • void findUser(String name) throws AppException
    • If name is empty string: throws ValidationException("Name cannot be empty")
    • If name is "unknown": throws NotFoundException("User not found: unknown")
    • Otherwise: prints "Found user: " + name
  • Main class
    • Creates a UserService instance
    • Calls findUser("") (ValidationException)
    • Calls findUser("unknown") (NotFoundException)
    • Calls findUser("Alice") (normal)
    • Each call is wrapped in try-catch, catching ValidationException, NotFoundException, AppException in order

Output Format

[VALIDATION] Name cannot be empty
[NOT_FOUND] User not found: unknown
Found user: Alice

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