Age Input Validation with Exceptions in Java: Explanation & Practice
Validate user input using exceptions
Problem summary
Validate age input: must be positive integer between 0-150.
Starter code
public class Main {
static void validateAge(String input) throws Exception {
// Validate and throw appropriate exceptions
}
public static void main(String[] args) {
String input = "25"; // Test case 1
// Validate and print result or error
}
}Expected output and test cases
- Valid input
Valid age: 25
- Non-numeric input
Error: Not a number
- Age > 150
Error: Age out of range
Hints
- Try Integer.parseInt()
- Catch NumberFormatException
- Check range after parsing
Related Exception Handling exercises
- Practice Exception Logging in Java
- Practice Retry Mechanism in Java
- Practice Aggregate Multiple Exceptions in Java
Practice all Exception Handling exercises · Run this idea in the Java compiler