「Java8」catchした例外Exceptionをスロー(throw)する

環境
JavaSE1.8
Eclipse 2019-12

書式
try {処理コード} catch (ArithmeticException e) { throw e;}
スローした例外はcatchで捕まえます。
throw eで例外のインスタンスをスローしています

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study;
public class CatchDemo {
public static void main(String[] args) {
try {
// funAメソッドを呼び出す
Cft.funA();
} catch (ArithmeticException e) {
System.out.println("ArithmeticException例外エラー22: " + e.getMessage());
}
System.out.println("処理完了です");
}
}
//クラスCftの定義
class Cft {
// staticメソッドを定義する
static void funA() {
try {
int avg = 23 / 0;
avg = avg + 12;
} catch (ArithmeticException e) { // ArithmeticExceptionの例外をキャッチ
System.out.println("ArithmeticException例外エラー11:" + e.getMessage());
throw e; // 例外をスローする
}
}
}
package com.arkgame.study; public class CatchDemo { public static void main(String[] args) { try { // funAメソッドを呼び出す Cft.funA(); } catch (ArithmeticException e) { System.out.println("ArithmeticException例外エラー22: " + e.getMessage()); } System.out.println("処理完了です"); } } //クラスCftの定義 class Cft { // staticメソッドを定義する static void funA() { try { int avg = 23 / 0; avg = avg + 12; } catch (ArithmeticException e) { // ArithmeticExceptionの例外をキャッチ System.out.println("ArithmeticException例外エラー11:" + e.getMessage()); throw e; // 例外をスローする } } }
package com.arkgame.study;

public class CatchDemo {
      public static void main(String[] args) {
            try {
                  // funAメソッドを呼び出す
                  Cft.funA();
            } catch (ArithmeticException e) {
                  System.out.println("ArithmeticException例外エラー22: " + e.getMessage());
            }
            System.out.println("処理完了です");
      }
}

//クラスCftの定義
class Cft {
      // staticメソッドを定義する
      static void funA() {
            try {
                  int avg = 23 / 0;
                  avg = avg + 12;
            } catch (ArithmeticException e) { // ArithmeticExceptionの例外をキャッチ
                  System.out.println("ArithmeticException例外エラー11:" + e.getMessage());
                  throw e; // 例外をスローする
            }
      }
}

実行結果
ArithmeticException例外エラー11:/ by zero
ArithmeticException例外エラー22: / by zero
処理完了です

Java

Posted by arkgame