Custom Exception: Creating Your Own
Problem Description
Custom Exception: Creating Your Own
In this problem, you will create a program that defines an InvalidAgeException custom exception class and implement an age validation method that correctly throws the exception for invalid age values and completes normally for valid ones.
Learning Objective: Learn to create custom exception classes and implement domain-specific error handling
Overview
Custom exceptions are exception classes defined to represent application-specific error situations. They are created by extending the Exception class.
Specifications
Implement an age validation system:
InvalidAgeExceptionclass:- Extends Exception
- constructor:
InvalidAgeException(String message)- Call parent class constructor
AgeValidatorclass:static void validateAge(int age) throws InvalidAgeException- If age is less than 0 or greater than 150, throw
InvalidAgeException - Message:
"Age must be between 0 and 150" - If valid: complete normally without throwing
- If age is less than 0 or greater than 150, throw
Mainclass:- Include a
mainmethod (for compilation)
- Include a
Test Method
Each test case calls AgeValidator.validateAge(int) directly and verifies:
- Valid ages (e.g., 0, 25, 150) do not throw an exception
- Invalid ages (e.g., -1, 151) throw
InvalidAgeExceptionwith message"Age must be between 0 and 150"
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