Validation with Exceptions in Java: Explanation & Practice
Validate input and throw appropriate exceptions
Problem summary
Create a User validation that throws specific exceptions for different validation failures.
Starter code
class ValidationException extends Exception {
public ValidationException(String msg) { super(msg); }
}
class User {
public static void validate(String name, int age, String email) throws ValidationException {
// Validate: name not empty, age 0-150, email contains @
// Throw ValidationException with specific message
}
}
public class Main {
public static void main(String[] args) {
try {
User.validate("", 25, "test@email.com");
} catch (ValidationException e) {
System.out.println(e.getMessage());
}
try {
User.validate("John", -5, "test@email.com");
} catch (ValidationException e) {
System.out.println(e.getMessage());
}
}
}Expected output and test cases
- Correct validation messages
Name cannot be empty Age must be between 0 and 150
Hints
- Check each condition in order
- Throw with descriptive message
- Early return pattern after validation
Related Exception Handling exercises
Practice all Exception Handling exercises · Run this idea in the Java compiler