Javaexamples-exception-catch

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

Javaの例-catchを使用して例外を処理する

問題の説明

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

溶液

この例は、catchを使用して例外を処理する方法を示しています。

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 (Exception e) {
         System.out.println("Exception occoured : "+e);
      }
   }
}

結果

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

The result is1
Exception occoured : java.lang.ArrayIndexOutOfBoundsException: 5

以下は、Javaで例外を処理するcatchの別の例です

public class Trycatch {
   public static void main(String args[]) {
      try {
         int data = 50/0;
      } catch(ArithmeticException e){System.out.println(e);}
      System.out.println("rest of the code...");
   }
}

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

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