019-001-006

Exception Handling: Age Validation

Hard

Problem Description

Exception Handling: Age Validation

Learning Objective: Understand how to detect invalid input by throwing exceptions and improve program safety

Overview

Create a method to validate age. When invalid values are entered, throw an exception to notify the caller of the error. Exceptions are "designed safety valves" and an important feature for keeping programs safe.

Specifications

AgeValidator Class

  • Method: void validateAge(int age)
    • If age is less than 0: throw IllegalArgumentException
      • Message: "Age must be positive or zero"
    • If age exceeds 150: throw IllegalArgumentException
      • Message: "Age must be 150 or less"
    • If in valid range (0-150): do nothing (don't throw exception)

Validation Logic

  • Detect invalid values early (early return pattern)
  • Provide clear error messages

Test Cases

  1. Valid value (25): No exception
  2. Boundary value (0): No exception
  3. Boundary value (150): No exception
  4. Invalid value (-5): IllegalArgumentException
  5. Invalid value (200): IllegalArgumentException

Ready to Try Running Code?

Log in to access the code editor and execute your solutions for this problem.

Don't have an account?