java.lang.IllegalArgumentException
java.lang.IllegalArgumentException
DodaTech
3 min read
java.lang.IllegalArgumentException is thrown when a method receives an argument that is outside the acceptable range or doesn’t meet the method’s preconditions.
What It Means
The method you called has specific requirements for its parameters (non-null, positive, within a range, etc.), and the value you passed violates one of those constraints. The method throws this exception before processing the invalid input.
Why It Happens
- You passed a negative number where a positive value is required.
- You passed a string that exceeds a maximum length limit.
- You passed an enum value that doesn’t match expected constants.
- A time or date value is out of the valid range.
- You passed a
nullwhere the method requires non-null (though this often throwsNullPointerExceptiondepending on the implementation).
How to Fix It
1. Read the error message
The exception message usually tells you exactly which parameter is invalid and what the expected range is:
// Example error:
// IllegalArgumentException: days: 367 (expected: 1-366)2. Validate inputs before calling the method
// BUG: passing invalid age
public void setAge(int age) {
if (age < 0 || age > 150) {
throw new IllegalArgumentException("age: " + age + " (expected: 0-150)");
}
this.age = age;
}
// Caller must validate first
public void registerUser(int age) {
if (age < 0 || age > 150) {
System.out.println("Invalid age: " + age);
return;
}
setAge(age);
}3. Use Objects.requireNonNull for null checking
public void processOrder(Order order, Discount discount) {
// Clear pre-condition checks at the top
Objects.requireNonNull(order, "order must not be null");
Objects.requireNonNull(discount, "discount must not be null");
// Guard against invalid values
if (order.getTotal() < 0) {
throw new IllegalArgumentException(
"order total must be non-negative, got: " + order.getTotal()
);
}
// Business logic below — safe to proceed
}4. Check API documentation for parameter constraints
// The Javadoc might specify:
// @throws IllegalArgumentException if start > end
// @throws IllegalArgumentException if step <= 0
IntStream.rangeClosed(10, 5) // throws: start 10 > end 5
IntStream.iterate(0, i -> i - 1) // fine — no constraint on step5. Use Preconditions from Google Guava
import com.google.common.base.Preconditions;
public void setPercentage(double value) {
Preconditions.checkArgument(
value >= 0.0 && value <= 100.0,
"percentage must be between 0 and 100, got: %s", value
);
this.percentage = value;
}Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro