📖 try / catch / finally の詳細解説
全体の構造
finally の使い道
├── ファイルを閉じる
├── データベース接続を切断する
└── リソースの解放
4. 動作の流れを図解
パターンA:例外が発生しない場合
try → 正常に実行 → finally → 次の処理へ
パターンB:例外が発生した場合
try → 例外発生! → catch → finally → 次の処理へ
5. 実践で確認しよう
両方のパターンを体験するコード
java
public class Main {
public static void main(String[] args) {
// パターンA:例外なし
System.out.println("=== パターンA ===");
try {
int result = 10 / 2;
System.out.println("結果: " + result);
} catch (ArithmeticException e) {
System.out.println("エラー: " + e.getMessage());
} finally {
System.out.println("パターンA 完了");
}
// パターンB:例外あり
System.out.println("\n=== パターンB ===");
try {
int result = 10 / 0;
System.out.println("結果: " + result);
} catch (ArithmeticException e) {
System.out.println("エラー: " + e.getMessage());
} finally {
System.out.println("パターンB 完了");
}
}
}
✅ 実行して、2つのパターンの違いを確認してください!
特に注目してほしい点:
パターンA: catchは実行される?されない?
パターンB: tryの中のprintlnは実行される?されない?