019-002-010

Custom Exception Definition

Easy

Problem Description

Custom Exception Definition

In this problem: You will define a custom exception class InvalidAgeException and use it for age validation.

Learning Objective: Understand how to define and throw custom exceptions

Overview

InvalidAgeException is a custom exception extending Exception. The Validator class's validateAge() method checks age and throws this exception for invalid values.

Specifications

  • InvalidAgeException: extends Exception. Has a constructor that accepts a message
  • Validator class: validateAge(int age) method
    • If age < 0: throws InvalidAgeException("Age cannot be negative: " + age)
    • If age > 150: throws InvalidAgeException("Age too large: " + age)
    • If valid: outputs "Valid age: {age}"
  • In Main, test with age = 25, -5, 200

Output Format

Valid age: 25
Error: Age cannot be negative: -5
Error: Age too large: 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