「Java」throwで例外をスローするサンプル

2022年1月17日

書式
throw 例外インスタンス
スローした例外はcatchで捕まえます

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package info;
class TestInfo {
static void funA() {
try {
int xx = 62 / 0;
// ArithmeticExceptionの例外をキャッチ
} catch (ArithmeticException e) {
System.out.println("エラーメッセージ11");
// throw eで例外のインスタンスをスローする
throw e;
}
}
}
public class ThrowDemo {
public static void main(String[] args) {
try {
TestInfo.funA();
// 例外をキャッチ
} catch (ArithmeticException e) {
System.out.println("エラーメッセージ22");
}
System.out.println("プログラムが終了です");
}
}
package info; class TestInfo { static void funA() { try { int xx = 62 / 0; // ArithmeticExceptionの例外をキャッチ } catch (ArithmeticException e) { System.out.println("エラーメッセージ11"); // throw eで例外のインスタンスをスローする throw e; } } } public class ThrowDemo { public static void main(String[] args) { try { TestInfo.funA(); // 例外をキャッチ } catch (ArithmeticException e) { System.out.println("エラーメッセージ22"); } System.out.println("プログラムが終了です"); } }
package info;

class TestInfo {
      static void funA() {
            try {
                  int xx = 62 / 0;
                  // ArithmeticExceptionの例外をキャッチ
            } catch (ArithmeticException e) {
                  System.out.println("エラーメッセージ11");
                  // throw eで例外のインスタンスをスローする
                  throw e;
            }
      }
}

public class ThrowDemo {

      public static void main(String[] args) {
            try {
                  TestInfo.funA();
                  // 例外をキャッチ
            } catch (ArithmeticException e) {
                  System.out.println("エラーメッセージ22");
            }
            System.out.println("プログラムが終了です");

      }

}

実行結果
エラーメッセージ11
エラーメッセージ22
プログラムが終了です

Java

Posted by arkgame