Input Validation with Exceptions in Java: Explanation & Practice

Validate user input using exceptions

Problem summary

Validate that input is a positive number, throw appropriate exception if not.

Starter code

public class Main {
    public static void main(String[] args) {
        String input = "-5"; // Test case 1
        
        // Parse and validate
        // Handle NumberFormatException and negative numbers
    }
}

Expected output and test cases

  • Negative input
    Error: Number must be positive
  • Non-numeric input
    Error: Invalid number format
  • Valid positive
    Valid input: 42

Hints

  1. First try to parse as integer
  2. Then check if positive
  3. Different messages for different errors

Related Exception Handling exercises

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