Tutorials Logic, IN info@tutorialslogic.com

IllegalArgumentException in Java: Causes, Fixes, Examples & Interview Tips

What is This Error?

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.

Common Causes

  • Passing a negative value where a positive is required
  • Passing null where a non-null value is required
  • Passing a value outside an expected range
  • Passing an empty string where content is required
  • Incorrect enum value or type mismatch

Quick Fix (TL;DR)

Quick Solution

Quick Solution
// ❌ 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;
}

Common Scenarios & Solutions

Solution

Solution
// ✅ 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;
}

Problem

Problem
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> sub = list.subList(3, 1); // ❌ fromIndex > toIndex!

Solution

Solution
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]
}

Problem

Problem
long delay = calculateDelay(); // Could return negative!
Thread.sleep(delay); // IllegalArgumentException if delay < 0!

Solution

Solution
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

Solution

Solution
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());
}

Best Practices to Avoid This Error

  • Validate all method arguments - Check at the start of every public method
  • Use Objects.requireNonNull() - For null checks with clear messages
  • Use Guava Preconditions - Clean, readable argument validation
  • Provide clear error messages - Include the invalid value in the message
  • Use Bean Validation (JSR-380) - @NotNull, @Min, @Max annotations
  • Document valid ranges in Javadoc - @throws IllegalArgumentException when...
  • Fail fast - Validate at the entry point, not deep in the call chain

Related Errors

Frequently Asked Questions

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.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.