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
Java Exceptions: try, catch, finally and throw
Exercises & Assignments
Create a custom exception for an invalid age
Interview Questions & Answers
What is an exception in Java? What are checked and unchecked exceptions?
What is the difference between final, finally and finalize in Java?
What is the difference between throw and throws in Java?
What are the best practices for exception handling in Java?