異常處理練習:處理求圓和長方形面積中的異常

需求:

2017.10.28.jpg

代碼:

/*
練習:處理求圓和長方形面積中的異常
*/
class NoValueException extends RuntimeException {   

   NoValueException(String msg) {
       super(msg);
   }
}

interface Shape {   

   void getArea();
}

class Rec implements Shape {
   
   private int len,wid;
   
   Rec(int len,int wid)  { //throws NoValueException 自定義異常繼承的是RuntimeException
                           //下面也不用進行異常處理了(不用try catch了
       if (len<=0 || wid<=0)
           throw new NoValueException("出現非法值");
       
       this.len = len;
       this.wid = wid;
   }
   
   public void getArea() {
       System.out.println(len*wid);
   }
}

class Circle implements Shape {
   
   private int radius;
   public static final double PI = 3.14; //全局常量
   
   Circle(int radius) {
       if (radius<=0)
           throw new NoValueException("非法");
       this.radius = radius;
   }
   
   public void getArea() {
       System.out.println(radius*radius*PI);
   }
}

class ExceptionText1 {

   public static void main(String[] args) {
       Rec r = new Rec(3,4);
       r.getArea();
       
       Circle c = new Circle(38);
       c.getArea();
       System.out.println("over");
   }
}

總結:

在實際中,異常處理要單獨封裝成一個類,這個類的名字便于查看具體是什么異常。對于非法值的異常,可以自定義一個類直接繼承RuntimeException異常類,此時不用再拋出異常和處理異常了,出現問題后虛擬機直接停止工作,便于直接改掉非法值,才繼續工作。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容