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
- Check lower bound first
- Then check upper bound
- Different messages for different violations
Related Exception Handling exercises
- Practice Retry with Exceptions in Java
- Practice Exception Propagation in Java
- Practice Password Validation in Java
Practice all Exception Handling exercises · Run this idea in the Java compiler