Create a custom exception for an invalid age

Description: Create a checked exception InvalidAgeException. Write a method register(int age) which throws it when the age is below 18, and catch it in main.

Hint:

  • Extend Exception, and use throws in the method line.

Solution

class InvalidAgeException extends Exception {
    InvalidAgeException(String message) {
        super(message);
    }
}

public class Main {
    static void register(int age) throws InvalidAgeException {
        if (age < 18) {
            throw new InvalidAgeException("Age " + age + " is below 18");
        }
        System.out.println("Registered, age " + age);
    }

    public static void main(String[] args) {
        for (int age : new int[]{25, 15}) {
            try {
                register(age);
            } catch (InvalidAgeException e) {
                System.out.println("Cannot register: " + e.getMessage());
            }
        }
    }
}
Output

Registered, age 25
Cannot register: Age 15 is below 18

How it works

  • Because the class extends Exception (not RuntimeException), it is checked: the compiler forces the caller to handle it.

Read Java Exceptions.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.