Checked Exception
JavaやSwiftにある
catchする処理を書かないとcompile errorになる
例外
コード例 by

javaimport java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class CheckedExample {
public static void main(String[] args) {
try {
String fileContent = readFile("example.txt");
System.out.println(fileContent);
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
}
// 型でthrowすることを明示する
public static String readFile(String fileName) throws IOException {
StringBuilder fileContent = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = reader.readLine()) != null) {
fileContent.append(line).append(System.lineSeparator());
}
}
return fileContent.toString();
}
}
例外を起こす関数
swiftfunc hoge() throws -> Int { ... }
型に throws
を明示する
使う
swiftfunc main() {
do {
// doの中でのみ呼び出せる
// tryを付ける必要がある
let a = try hoge()
} catch {
showError(error)
}
}
対義語
tsの例外とかはこれだね

Javaで導入されたChecked Exceptionが流行らなかった理由
checked exception自体は良いが、他が微妙すぎて使い物にならないらしい
例えば、null安全でないとか
例えば、Checked Exceptionだけ捕捉するのが困難とか
(予測できる)Checked Exception用のhandlerを書くと、
予測できないUnchecked Exceptionも補足されてしまう