- 最終更新
- 2026/08/17
3秒でわかる
実行中に起きたエラーを捕まえて、処理の続きを決める仕組み。try と catch と finally で異常時の振る舞いを組み立てます。
30秒図解
もう少し詳しく
どういうものか
例外処理は、try がcatch がfinally が
例外がtry 内のcatch へcatch が
なぜ必要か
正常系のif が
finally が
具体例
public int readCount(String path) {
try {
String text = Files.readString(Path.of(path));
return Integer.parseInt(text.trim());
} catch (NoSuchFileException e) {
// ファイルが無いのは想定内なので既定値で続ける
return 0;
} catch (IOException e) {
// 読み取り失敗は呼び出し元へ知らせる
throw new UncheckedIOException(e);
} catch (NumberFormatException e) {
throw new IllegalStateException("数値として読めない内容です", e);
}
}リソースの解放は finally にtry に
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
} // close は自動で呼ばれるつまずきやすいところ
捕まえてcatch が
try {
risky();
} catch (Exception e) {
// 何も書かない
}これは
Exception でNullPointerException まで
もうひとつ、finally の中で return すると、try や catch のfinally には
覚え方
例外処理は


