019-004-006

Custom Exception: Creating Your Own

Medium

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:

  1. InvalidAgeException class:

    • Extends Exception
    • constructor: InvalidAgeException(String message)
      • Call parent class constructor
  2. AgeValidator class:

    • 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
  3. Main class:

    • Include a main method (for compilation)

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 InvalidAgeException with 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