<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 switch with a default that 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

IllegalArgumentExceptionIllegalStateException
What's wrongCaller passed a bad valueObject is in a bad state for this call
ExamplesetAge(-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 β€” IllegalArgumentException is 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.