標籤:
import java.util.*;import java.text.*;class ChineseDate{ private Calendar aday; public ChineseDate(int year, int month,int day)throws MyDateException{ //this.aday= new Calendar();//不行,因為Calendar是抽象類別 //this(); this.aday = Calendar.getInstance(); //※※※ this.set(year,month,day); } public ChineseDate(){ this.aday = Calendar.getInstance(); } public void set(int year, int month, int day)throws MyDateException{//拋異常 //進行商務邏輯的合法性處理 if(year<=0 || year>2500){ throw new MyDateException("年份錯誤,有效年份為:0~2500。"); } if(month<=0 || month>12){ throw new MyDateException("月份錯誤!"); } if(day<=0 || day>daysOfMonth(year,month) ){ throw new MyDateException("日期錯誤"); } this.aday.set(year,month-1,day); //※※※ } public static boolean isLeapYear( int year ){ boolean boo=year%400==0 || year%100!=0&&year%4==0; return boo; } public boolean isLeapYear(){ return this.isLeapYear(aday.get(Calendar.YEAR)); } public static int daysOfMonth(int year,int month){ switch(month){ case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31; case 4: case 6: case 9: case 11: return 30; case 2: return isLeapYear(year)? 29:28; default: return 0; } } /* //※※※ public int daysOfMonth(){ return daysOfMonth(aday.get(Calendar.YEAR),aday.get(Calendar.MONTH)); } */ public String toString(){ return new SimpleDateFormat("yyyy年MM月dd日 EEEEE a hh 時 mm 分 ss 秒").format( new Date(aday.getTimeInMillis()) ); } public static void main(String args[]){ try{//接異常 ,異常處理 System.out.println( new ChineseDate(2015,1,23) ); }catch(MyDateException e){ System.out.println("aaaa----:"+e.toString() ); if(e.toString().equals("年份錯誤,有效年份為:0~2500。")){ System.out.println("發現年份出錯的異常,進行相應處理...."); } if(e.toString().equals("月份錯誤!")){ System.out.println("發現月份出錯的異常,進行相應處理...."); } if(e.toString().equals("日期錯誤")){ System.out.println("發現日期出錯的異常,進行相應處理...."); } }catch(Exception e){ e.printStackTrace(); } System.out.println("我很好..."); }}
java之------ 異常處理