MeWrite Docs

IllegalArgumentException

Javaでメソッドに不正な引数が渡された場合に発生するエラー

概要

IllegalArgumentException は、Javaでメソッドに不正な引数や不適切な値が渡された場合に発生する実行時例外です。

エラーメッセージ

Exception in thread "main" java.lang.IllegalArgumentException: timeout value is negative
java.lang.IllegalArgumentException: Comparison method violates its general contract!

原因

1. 負の値が許可されない場合

1
Thread.sleep(-1000); // IllegalArgumentException

2. null以外の空文字列

1
new URL(""); // IllegalArgumentException

3. Comparatorの実装ミス

1
2
3
4
5
6
// 推移律に違反するComparator
Collections.sort(list, (a, b) -> {
    if (a > b) return 1;
    if (a < b) return -1;
    return 1; // 等しい場合も1を返すのは違反
});

解決策

1. 事前バリデーション

1
2
3
4
5
6
public void setTimeout(long timeout) {
    if (timeout < 0) {
        throw new IllegalArgumentException("timeout must be non-negative");
    }
    this.timeout = timeout;
}

2. Objects.requireNonNull

1
2
3
public void setName(String name) {
    this.name = Objects.requireNonNull(name, "name must not be null");
}

3. 正しいComparator実装

1
2
3
4
5
6
Collections.sort(list, (a, b) -> {
    return Integer.compare(a, b);
});

// または Comparator.comparing
list.sort(Comparator.comparing(User::getName));

4. Apache Commons Validate

1
2
3
4
5
6
import org.apache.commons.lang3.Validate;

public void process(String input, int count) {
    Validate.notBlank(input, "input must not be blank");
    Validate.isTrue(count > 0, "count must be positive");
}

関連エラー

関連エラー

Java の他のエラー

最終更新: 2025-12-17