根据以下要求编写JAVA代码并写出运行结果。1.现编写一个自定义的异常InvalidDateException。当构造方法或设置方法接受的参数不符合实际要求时,抛出一个这个异常的实例。2.在main方法中分别包含以下代码,捕获并打印异常信息3.MyDated1=newMyDate(-1,13,32);4.MyDated2=newMyDate();d2.setDay(100)
时间: 2023-06-25 19:07:28 浏览: 177
JAVA 自定义异常 Exception
4星 · 用户满意度95%
代码实现如下:
```
public 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 {
setYear(year);
setMonth(month);
setDay(day);
}
public MyDate() {
this.year = 2022;
this.month = 12;
this.day = 31;
}
public int getYear() {
return year;
}
public void setYear(int year) throws InvalidDateException {
if (year < 0) {
throw new InvalidDateException("Invalid year: " + year);
}
this.year = year;
}
public int getMonth() {
return month;
}
public void setMonth(int month) throws InvalidDateException {
if (month < 1 || month > 12) {
throw new InvalidDateException("Invalid month: " + month);
}
this.month = month;
}
public int getDay() {
return day;
}
public void setDay(int day) throws InvalidDateException {
if (day < 1 || day > 31) {
throw new InvalidDateException("Invalid day: " + 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 year: -1
Invalid day: 100
```
阅读全文