在实验三中曾经实现过日期类MyDate,它包含一个含参数的构造方法MyDate(intyear,intmonth,intday)、以及三个相应的设置方法setXXX(intarg)。1.现编写一个自定义的异常InvalidDateException。当构造方法或设置方法接受的参数不符合实际要求时,抛出一个这个异常的实例。2.在main方法中分别包含以下代码,捕获并打印异常信息:MyDated1=newMyDate(-1,13,32);MyDated2=newMyDate();d2.setDay(100);
时间: 2023-06-26 10:08:26 浏览: 217
以下是实现代码:
```java
class InvalidDateException extends Exception {
public InvalidDateException(String message) {
super(message);
}
}
class MyDate {
private int year;
private int month;
private int day;
public MyDate(int year, int month, int day) throws InvalidDateException {
if (year <= 0 || month <= 0 || month > 12 || day <= 0 || day > 31) {
throw new InvalidDateException("Invalid date");
}
this.year = year;
this.month = month;
this.day = day;
}
public MyDate() {
this.year = 1;
this.month = 1;
this.day = 1;
}
public void setYear(int year) throws InvalidDateException {
if (year <= 0) {
throw new InvalidDateException("Invalid year");
}
this.year = year;
}
public void setMonth(int month) throws InvalidDateException {
if (month <= 0 || month > 12) {
throw new InvalidDateException("Invalid month");
}
this.month = month;
}
public void setDay(int day) throws InvalidDateException {
if (day <= 0 || day > 31) {
throw new InvalidDateException("Invalid day");
}
this.day = day;
}
}
public class Main {
public static void main(String[] args) {
try {
MyDate d1 = new MyDate(-1, 13, 32);
} catch (InvalidDateException e) {
System.out.println(e.getMessage());
}
MyDate d2 = new MyDate();
try {
d2.setDay(100);
} catch (InvalidDateException e) {
System.out.println(e.getMessage());
}
}
}
```
输出结果为:
```
Invalid date
Invalid day
```
阅读全文