码迷,mamicode.com
首页 > 编程语言 > 详细

java之------ 异常处理

时间:2015-05-02 13:56:51      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:


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之------ 异常处理

标签:

原文地址:http://blog.csdn.net/u011479875/article/details/45438561

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!