πŸ”§ Error Fixes
Β· 1 min read

Java IllegalArgumentException β€” How to Fix It


java.lang.IllegalArgumentException: Invalid argument
java.lang.IllegalArgumentException: timeout value is negative

A method was called with an argument that’s not valid β€” wrong range, null when not allowed, or wrong format.

Fix 1: Validate Input Before Passing

// ❌ Passing negative value
Thread.sleep(-1000);  // πŸ’₯ IllegalArgumentException

// βœ… Validate first
if (timeout > 0) {
    Thread.sleep(timeout);
}

Fix 2: Null Argument

// ❌ Passing null to a method that doesn't accept it
Path path = Paths.get(null);  // πŸ’₯

// βœ… Check for null
if (filename != null) {
    Path path = Paths.get(filename);
}

Fix 3: Enum.valueOf with Invalid Name

// ❌ String doesn't match any enum constant
Color c = Color.valueOf("PURPLE");  // πŸ’₯ If PURPLE doesn't exist

// βœ… Handle gracefully
try {
    Color c = Color.valueOf(input.toUpperCase());
} catch (IllegalArgumentException e) {
    Color c = Color.RED;  // Default
}

Fix 4: Date/Time Parsing

// ❌ Invalid date format
LocalDate.parse("2026-13-01");  // πŸ’₯ Month 13 doesn't exist

// βœ… Validate or catch
try {
    LocalDate date = LocalDate.parse(input);
} catch (DateTimeParseException e) {
    System.out.println("Invalid date: " + input);
}

Fix 5: Collection Operations

// ❌ fromIndex > toIndex
list.subList(5, 2);  // πŸ’₯

// βœ… Ensure correct order
int from = Math.min(a, b);
int to = Math.max(a, b);
list.subList(from, to);