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

  1. Try Integer.parseInt()
  2. Catch NumberFormatException
  3. Check range after parsing

Related Exception Handling exercises

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