<code>IllegalArgumentException</code> in Java
IllegalArgumentException is an unchecked exception you throw to reject caller-supplied values that can't be processed β a negative age, an empty string where a name is required, a date outside an allowed range.
When to throw it
- A parameter value violates a documented precondition.
- Arguments are individually valid but their combination isn't (e.g.
from > to). - A value isn't a recognised option in a fixed set (consider a
switchwith adefaultthat throws).
Canonical precondition pattern
public Order charge(BigDecimal amount) {
if (amount == null) {
throw new IllegalArgumentException("amount must not be null");
}
if (amount.signum() < 0) {
throw new IllegalArgumentException("amount must be positive, got " + amount);
}
...
}
Helpers
// java.util.Objects
Objects.requireNonNull(name, "name"); // throws NPE β not IAE
Objects.checkIndex(i, length); // throws IndexOutOfBoundsException
// Guava (com.google.common.base.Preconditions)
Preconditions.checkArgument(amount.signum() >= 0, "amount must be >= 0, got %s", amount);
Preconditions.checkNotNull(user, "user");
IllegalArgument vs IllegalState
| IllegalArgumentException | IllegalStateException | |
|---|---|---|
| What's wrong | Caller passed a bad value | Object is in a bad state for this call |
| Example | setAge(-1) | iterator.remove() before next() |
Include the bad value in the message
// β Useless
throw new IllegalArgumentException("invalid age");
// β
Actionable
throw new IllegalArgumentException("age must be 0-150, got " + age);
Common mistakes
- Silently clamping bad input β
if (age < 0) age = 0;hides bugs. Throw. - Using a generic
RuntimeExceptionβIllegalArgumentExceptionis more specific and tells the reader exactly whose fault it is. - Catching and ignoring β if an argument is invalid, the caller should see it, not log-and-continue.
Related
Pillar: Java exceptions. Siblings: NullPointerException, Custom exceptions.