019-002-009

Custom Age Validation Exception

Medium

Problem Description

Custom Age Validation Exception

In this problem: You will create a custom exception class InvalidAgeException extending Exception, and an AgeValidator class with a validate(int age) method that throws this exception for ages below 0 or above 150. The Main class catches the exceptions using try-catch and displays the messages to standard output.

Learning Objective: Understand how to create custom exception classes and the throw-catch workflow

Overview

In Java, you can create custom exception classes by extending the Exception class. In this problem, you will build a validator that checks age values and throws a custom exception for invalid inputs.

Specifications

InvalidAgeException Class (InvalidAgeException.java)

  • Extends Exception
  • Constructor: InvalidAgeException(String message) calls super(message)

AgeValidator Class (AgeValidator.java)

  • void validate(int age) throws InvalidAgeException
  • If age < 0: Throw exception with message "Age cannot be negative: " + age
  • If age > 150: Throw exception with message "Age cannot exceed 150: " + age
  • For valid values: Print "Valid age: " + age

Main Class (Main.java)

  • Create an AgeValidator instance
  • Call validate(25) (normal case)
  • Call validate(-5) (triggers exception)
  • Call validate(200) (triggers exception)
  • Wrap each call in a separate try-catch block, printing "Error: " + exception message in catch

Output Format

Valid age: 25
Error: Age cannot be negative: -5
Error: Age cannot exceed 150: 200

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