Exception với overload trong Java



Miêu tả vấn đề

Cách xử lý Exception với overload (nạp chồng) phương thức trong Java?

Giải pháp

Ví dụ sau minh họa cách xử lý Exception với overload (nạp chồng) phương thức trong Java. Bạn cần có một khối try…catch trong mỗi phương thức.

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);
      }
   }
}

Kết quả

Code trên sẽ cho kết quả sau:

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

exception_trong_java.jsp