Error Handling
Exception: checked と unchecked は呼び出し側の契約が違う
IOException は呼び出し側で扱うことを型で求め、IllegalArgumentException は実行時に送出します。
SourceExceptionKinds.java
Java 21
package examples.exceptionhandling;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public final class ExceptionKinds {
private ExceptionKinds() {}
public static String read(Path path) throws IOException {
return Files.readString(path);
}
public static int requirePositive(int value) {
if (value <= 0) {
throw new IllegalArgumentException("value must be positive");
}
return value;
}
}TestExceptionKindsTest.java
Java 21
package examples.exceptionhandling;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.IOException;
import java.nio.file.Path;
import org.junit.jupiter.api.Test;
class ExceptionKindsTest {
@Test
void 存在しないファイルの読み込みはcheckedのIOExceptionを送出する() {
assertThrows(IOException.class, () -> ExceptionKinds.read(Path.of("missing-file.txt")));
}
@Test
void 不正な引数はuncheckedのIllegalArgumentExceptionを送出する() {
assertThrows(IllegalArgumentException.class, () -> ExceptionKinds.requirePositive(0));
}
}01Assertion
このテストで確認できること
- ファイル読み込みメソッドは checked 例外として IOException を宣言する
- 不正な値は unchecked の IllegalArgumentException を送出する
復旧を呼び出し側に求める失敗は checked 例外、プログラム上の前提違反は unchecked 例外として使い分けます。
OBSERVED RESULT
expected exception: IOException
expected exception: IllegalArgumentException