java異常練習2,java練習2
/*
有一個圓形和長方形
都可以擷取面積,對於面積,如果出現非法數值,視為擷取面積出現問題
問題通過異常來表示。
先要對這個程式進行基本的設定
*/
/*首先想一下,怎麼寫這個程式
基本屬性是肯定要的
求面積呢?
1.可以定義成函數
2.可以定義成介面
3.或者資料庫什麼的
*/
1 interface Shape /*可以直接列印,可以返回*/ 2 { 3 void getArea(); /*要傳遞參數嗎?不需要,因為這是抽象類別,需要把一些共同的屬性抽取出來,這裡並沒有,需要重寫,這裡重新擷取就可以*/ 4 } 5 class NoValueException extends RuntimeException 6 { 7 NoValueException(String message) /*建構函式*/ 8 { 9 super(message); /*調用父類的建構函式*/ /*這裡是父類的錯誤資訊,直接能夠賦值的*/10 }11 }12 class Cricle implements Shape13 { 14 private int radius;15 public static final double PI=3.14;16 Cricle(int radius)17 {18 if(radius<0)19 throw new RunTimeException("非法"); /*使用這個異常名稱不好,不好處理問題,應該自訂名稱*/20 this.radius=radius;21 }22 public void getArea()23 {24 System.out.println(radius*radius*PI); /*不需要改動的值起一個名字 PI*/25 }26 }27 28 29 class Rec implements Shape /*長方形*/30 {31 private int len,wid; /*定義長和寬*/32 Rec(int len,int wid) /*這哥們一初始化就有這個東西*/33 {34 if(len<=0||wid<=0)35 {36 throw new NoValueException("出現非法值");37 }38 39 this.len=len; /*進行賦值*/40 this.wid=wid;41 42 }43 public void getArea() /*進行重寫*/44 {45 System.out.println(len*wid); /*直接列印輸出面積*/46 }47 }48 49 50 class ExceptionText151 {52 public static void main(String args[])53 {54 //try /*檢測代碼塊*/55 //{56 Rec r=new Rec(3,4); /*你發現輸入負數,面積為負數,這是不允許的,以前用if避免,但現在,請你用*/57 r.getArea(); /*如果上面的代碼出現了錯誤,這塊就不運行了*/58 //}59 //catch(NoValueException e) /*接收異常,這種處理是沒有用的*/60 //{61 //System.out.println(e.toString()); /*輸出異常資訊*/62 //}63 System.out.println("over"); /*最後輸出*/ /*然而運行這是沒有用的,還不如直接用運行時異常,不需要檢查捕捉處理,直接停掉*/64 }65 }