Javaexamples-exception-chain

提供:Dev Guides
移動先:案内検索

Javaの例-連鎖例外

問題の説明

catchを使用して連鎖例外を処理する方法は?

溶液

この例は、複数のcatchブロックを使用して連鎖例外を処理する方法を示しています。

public class Main{
   public static void main (String args[])throws Exception {
      int n = 20, result = 0;
      try {
         result = n/0;
         System.out.println("The result is "+result);
      } catch(ArithmeticException ex) {
         System.out.println ("Arithmetic exception occoured: "+ex);
         try {
            throw new NumberFormatException();
         } catch(NumberFormatException ex1) {
            System.out.println ("Chained exception thrown manually : "+ex1);
         }
      }
   }
}

結果

上記のコードサンプルは、次の結果を生成します。

Arithmetic exception occoured :
java.lang.ArithmeticException:/by zero
Chained exception thrown manually :
java.lang.NumberFormatException

以下は、キャッチを使用してJavaで連鎖例外を処理する別の例です。

public class Main{
   public static void main (String args[])throws Exception  {
      int n = 20,result = 0;
      try{
         result = n/0;
         System.out.println("The result is"+result);
      }catch(ArithmeticException ex){
         System.out.println("Arithmetic exception occoured: "+ex);
         try{
            int data = 50/0;
         }catch(ArithmeticException e){System.out.println(e);}
            System.out.println("rest of the code...");
      }
   }
}

上記のコードサンプルは、次の結果を生成します。

Arithmetic exception occoured: java.lang.ArithmeticException:/by zero
java.lang.ArithmeticException:/by zero
rest of the code...