🔧 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);