019-006-005
Custom Exception: User-Defined Exception
Easy
Problem Description
Custom Exception: User-Defined Exception
In this problem, you will create a program that defines a custom exception class InvalidAgeException extending Exception, and throws it when the age value is negative.
Learning Objective: Learn to create and use custom exception classes
Overview
By extending Exception class, you can create application-specific exceptions. This makes error handling clearer.
Specifications
InvalidAgeException class (InvalidAgeException.java)
- Extends
Exception - Constructor:
InvalidAgeException(String message)- Pass message to parent class via
super(message)
- Pass message to parent class via
Main class (Main.java)
static void validateAge(int age) throws InvalidAgeException- If age is less than 0, throw
InvalidAgeException - Message:
"Age cannot be negative" - If valid: complete normally without throwing
- If age is less than 0, throw
- Include a
mainmethod (for compilation)
Test Method
Each test case calls Main.validateAge(int) directly and verifies:
- Valid ages (e.g., 0, 25, 100) do not throw an exception
- Invalid ages (e.g., -1, -5) throw
InvalidAgeExceptionwith message"Age cannot be negative"
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