public class Test extends Exception{
public static void main(String[] args) throws Exception {
try {
MyDate d1 = new MyDate(1999, 1, 1);
MyDate d2 = new MyDate(2009, 4, 1);
MyDate d3 = new MyDate(a, 1, 1);
MyDate d4=new MyDate(-1, 13, 32);
d1.print();
d2.print();
d3.print();
d4.print();
}catch (Exception e) {
throw new Exception("\n自定义异常类!");
}
}
}
请问,如果我要捕获这个d3创建对象错误,数据类型不匹配,如何捕获呢,我试了很多方法,都不能成功!
不会显示我要输出的语句。直接出现系统错误。
程序的类代码:
public class MyDate extends Exception{
//属性:
private int year,month,day;
boolean isRunyear;
//构造器:
public MyDate(){
this.year=1999;
this.month=1;
this.day=1;
}
public MyDate(int year, int month, int day){
try {
setYear(year);
setMonth(month);
setDay(day);
}catch (Exception e){
System.out.println("Error!");
}
}
//方法:
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
public String isRunyear(){
if(year%4==0&&year%100!=0){
isRunyear=true;
}
if(isRunyear==true) {
return "闰年!";
} else{
return "不是闰年!";
}
}
public void print(){
if(year<0) {
System.out.println("年份不能为负数!");
}else {
System.out.println(getYear() + "年" + getMonth() + "月" + getDay() + "日 " + isRunyear());
}
}
}