019-006-008

Defining Custom Exception Class

Easy

Problem Description

Defining Custom Exception Class

In this problem, you will create a program that defines a custom exception class AgeException extending Exception, and throws it from an age validation method.

Learning Objective: Understand how to define custom exception classes by extending Exception and throw exceptions with throw

Overview

Java allows defining custom exception classes to represent application-specific error conditions. Create a custom exception by extending the Exception class.

Specifications

AgeException class (AgeException.java)

  • Extends Exception
  • Constructor: AgeException(String message)
    • Pass message to parent class via super(message)

Main class (Main.java)

  • static void validateAge(int age) throws AgeException
    • If age is less than 0 or greater than 150, throw AgeException
    • Message: "Age X is out of valid range (0-150)" (X is the argument value)
    • If valid: complete normally without throwing
  • Include a main method (for compilation)

Test Method

Each test case calls Main.validateAge(int) directly and verifies:

  • Valid ages (e.g., 25, 100) do not throw an exception
  • Invalid ages (e.g., -5, 200) throw AgeException with the correct message

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