Javaexamples-exception-overloaded-method

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

Javaの例-オーバーロードされたメソッドの例外

問題の説明

オーバーロードされたメソッドで例外を処理する方法は?

溶液

この例は、オーバーロードされたメソッドで例外を処理する方法を示しています。 各メソッドまたは使用される場所にtry catchブロックが必要です。

public class Main {
   double method(int i) throws Exception {
      return i/0;
   }
   boolean method(boolean b) {
      return !b;
   }
   static double method(int x, double y) throws Exception {
      return x + y ;
   }
   static double method(double x, double y) {
      return x + y - 3;
   }
   public static void main(String[] args) {
      Main mn = new Main();
      try {
         System.out.println(method(10, 20.0));
         System.out.println(method(10.0, 20));
         System.out.println(method(10.0, 20.0));
         System.out.println(mn.method(10));
      } catch (Exception ex) {
         System.out.println("exception occoure: "+ ex);
      }
   }
}

結果

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

30.0
27.0
27.0
exception occoure: java.lang.ArithmeticException:/by zero

以下は、Javaのオーバーロードメソッドで例外を処理する別の例です。

class NewClass1 {
   void msg()throws Exception{System.out.println("this is parent");}
}
public class NewClass extends NewClass1 {
   NewClass() {
   }
   void msg()throws ArithmeticException{System.out.println("This is child");}
   public static void main(String args[]) {
      NewClass1 n = new NewClass();
      try {
         n.msg();
      } catch(Exception e){}
   }
}

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

This is child