Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

IllegalArgumentException in Java — How to Fix (2026) | Tutorials Logic

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
// ❌ 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

Scenario 1: Validate Method Arguments

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;
}

Scenario 2: List.subList() Invalid Range

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

int from = 1, to = 3;
if (from <= to && from >= 0 && to <= list.size()) {
    List sub = list.subList(from, to); // ✅ [2, 3]
}

Scenario 3: Thread.sleep() Negative Value

Problem
long delay = calculateDelay(); // Could return negative!
Thread.sleep(delay); // IllegalArgumentException if delay < 0!
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

Scenario 4: Catching and Handling

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

Key Takeaways
  • IllegalArgumentException signals that a method received an invalid argument
  • Validate all method arguments at the start of public methods
  • Use Objects.requireNonNull() for null checks with descriptive messages
  • Include the invalid value in the exception message for easier debugging
  • Use Guava Preconditions or Bean Validation for clean validation code
  • Document valid argument ranges in Javadoc with @throws IllegalArgumentException

Frequently Asked Questions


Ready to Level Up Your Skills?

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