Age Range Validator in Java: Explanation & Practice

Validate age is within acceptable range

Problem summary

Create a validator that ensures age is between 0 and 150, with specific error messages.

Starter code

// Validate age: 0-150
// Throw appropriate exceptions with messages

public class Main {
    public static void main(String[] args) {
        int age = -5; // Test case 1
        
        // Validate and handle exceptions
    }
}

Expected output and test cases

  • Negative age
    Error: Age cannot be negative
  • Too old
    Error: Age cannot exceed 150
  • Valid age
    Valid age: 25

Hints

  1. Check lower bound first
  2. Then check upper bound
  3. Different messages for different violations

Related Exception Handling exercises

Practice all Exception Handling exercises · Run this idea in the Java compiler