0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Java. { Try Catch. Finally}

0
Posted at

📖 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は実行される?されない?

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?