Javaexamples-exception-multiple1

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

Javaの例-複数の例外(範囲外の配列)

問題の説明

配列が範囲外のときに複数の例外を処理する方法は?

溶液

この例は、SystemクラスのSystem.err.println()メソッドを使用して複数の例外メソッドを処理する方法を示しています。

public class Main {
   public static void main (String args[]) {
      int array[] = {20,20,40};
      int num1 = 15, num2 = 10;
      int result = 10;
      try {
         result = num1/num2;
         System.out.println("The result is" +result);
         for(int i = 5; i >= 0; i--) {
            System.out.println("The value of array is" +array[i]);
         }
      } catch (ArrayIndexOutOfBoundsException e) {
         System.out.println("Array is out of Bounds"+e);
      } catch (ArithmeticException e) {
         System.out.println ("Can't divide by Zero"+e);
      }
   }
}

結果

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

The result is1
Array is out of Boundsjava.lang.ArrayIndexOutOfBoundsException : 5