根据以下要求编写JAVA代码并写出运行结果,每行代码都要带有注释。1.现编写一个自定义的异常InvalidDateException。当构造方法或设置方法接受的参数不符合实际要求时,抛出一个这个异常的实例。2.在main方法中分别包含以下代码,捕获并打印异常信息3.MyDated1=newMyDate(-1,13,32);4.MyDated2=newMyDate();d2.setDay(100)
时间: 2023-06-25 11:08:04 浏览: 89
JAVA 自定义异常 Exception
4星 · 用户满意度95%
```
// 自定义异常类
class InvalidDateException extends Exception {
public InvalidDateException(String message) {
super(message);
}
}
// MyDate 类,用于表示日期
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() {
year = 2021;
month = 7;
day = 19;
}
public int getYear() { return year; }
public int getMonth() { return month; }
public int getDay() { return day; }
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 < 1 || month > 12) {
throw new InvalidDateException("Invalid month");
}
this.month = month;
}
public void setDay(int day) throws InvalidDateException {
if (day < 1 || day > 31) {
throw new InvalidDateException("Invalid day");
}
this.day = day;
}
}
public class Main {
public static void main(String[] args) {
try {
// 测试1:传入非法参数
MyDate d1 = new MyDate(-1, 13, 32);
} catch (InvalidDateException e) {
System.out.println(e.getMessage());
}
// 测试2:设置非法日期
MyDate d2 = new MyDate();
try {
d2.setDay(100);
} catch (InvalidDateException e) {
System.out.println(e.getMessage());
}
阅读全文