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
- First try to parse as integer
- Then check if positive
- Different messages for different errors
Related Exception Handling exercises
- Practice Try-With-Resources in Java
- Practice Custom Exception Class in Java
- Practice Exception Chaining in Java
Practice all Exception Handling exercises · Run this idea in the Java compiler