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(extendsException): Has a constructor that accepts a messageValidationException(extendsAppException): Has a constructor that accepts a messageNotFoundException(extendsAppException): Has a constructor that accepts a messageUserServiceclassvoid findUser(String name) throws AppException- If name is empty string: throws
ValidationException("Name cannot be empty") - If name is
"unknown": throwsNotFoundException("User not found: unknown") - Otherwise: prints
"Found user: " + name
Mainclass- Creates a
UserServiceinstance - Calls
findUser("")(ValidationException) - Calls
findUser("unknown")(NotFoundException) - Calls
findUser("Alice")(normal) - Each call is wrapped in try-catch, catching
ValidationException,NotFoundException,AppExceptionin order
- Creates a
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