The IllegalArgumentException is thrown to indicate that a method has been passed an illegal or inappropriate argument. It's an unchecked exception used for input validation "” signaling that the caller passed an invalid value.
// ❌ Problem "” negative age
void setAge(int age) {
this.age = age; // No validation!
}
setAge(-5); // Silently accepts invalid value
// ✅ Solution "” validate and throw
void setAge(int age) {
if (age < 0 || age > 150) {
throw new IllegalArgumentException("Age must be between 0 and 150, got: " + age);
}
this.age = age;
}
// ✅ Use Objects.requireNonNull for null checks
public void setName(String name) {
this.name = Objects.requireNonNull(name, "Name cannot be null");
}
// ✅ Use Guava Preconditions
import com.google.common.base.Preconditions;
public void setAge(int age) {
Preconditions.checkArgument(age >= 0 && age <= 150,
"Age must be 0-150, got: %s", age);
this.age = age;
}
// ✅ Manual validation
public void setScore(double score) {
if (score < 0.0 || score > 100.0) {
throw new IllegalArgumentException(
"Score must be between 0 and 100, got: " + score);
}
this.score = score;
}
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> sub = list.subList(3, 1); // ❌ fromIndex > toIndex!
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
int from = 1, to = 3;
if (from <= to && from >= 0 && to <= list.size()) {
List<Integer> sub = list.subList(from, to); // ✅ [2, 3]
}
long delay = calculateDelay(); // Could return negative!
Thread.sleep(delay); // IllegalArgumentException if delay < 0!
long delay = calculateDelay();
if (delay > 0) {
Thread.sleep(delay); // ✅ Only sleep if positive
}
// Or use Math.max
Thread.sleep(Math.max(0, delay)); // ✅ Minimum 0
try {
user.setAge(Integer.parseInt(ageInput));
} catch (NumberFormatException e) {
System.out.println("Please enter a valid number");
} catch (IllegalArgumentException e) {
System.out.println("Invalid age: " + e.getMessage());
}
Throw it when a method receives an argument that violates its contract "” negative values where positive is required, null where non-null is expected, or values outside a valid range.
IllegalArgumentException is about invalid input to a method. IllegalStateException is about the object being in an invalid state for the operation (e.g., calling close() on an already-closed resource).
Use Objects.requireNonNull() which throws NullPointerException for null arguments. Some prefer IllegalArgumentException for null checks "” both are acceptable, but be consistent.
Guava's Preconditions class provides static methods like checkArgument(), checkNotNull(), and checkState() for clean, readable validation. They throw appropriate exceptions with formatted messages.
Add @Valid to method parameters and use annotations like @NotNull, @Min(0), @Max(150) on the parameter class fields. Enable method validation with Spring's @Validated on the class.
Explore 500+ free tutorials across 20+ languages and frameworks.