1. (论述题) 1、自定义异常类:年龄异常 输出错误提示:非正常学生年龄 2、学生类:姓名,性别,年龄 Setter年龄,检查小于15,大于80,抛出“年龄异常”给上级 3、测试类 录入学生信息,输入年龄 捕捉非数字异常,异常时显示信息:输入年龄不是数字 捕捉年龄异常,异常时显示信息:非正常学生年龄 如果正常,getter方法输出学生信息
时间: 2023-12-03 08:41:55 浏览: 49
自定义异常类:年龄异常
```java
public class AgeException extends Exception {
public AgeException() {
super("非正常学生年龄");
}
}
```
学生类:姓名,性别,年龄
```java
public class Student {
private String name;
private String gender;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) throws AgeException {
if (age < 15 || age > 80) {
throw new AgeException();
}
this.age = age;
}
}
```
测试类
```java
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Student student = new Student();
System.out.print("请输入学生姓名:");
student.setName(scanner.nextLine());
System.out.print("请输入学生性别:");
student.setGender(scanner.nextLine());
try {
System.out.print("请输入学生年龄:");
int age = Integer.parseInt(scanner.nextLine());
student.setAge(age);
System.out.println("学生信息:");
System.out.println("姓名:" + student.getName());
System.out.println("性别:" + student.getGender());
System.out.println("年龄:" + student.getAge());
} catch (NumberFormatException e) {
System.out.println("输入年龄不是数字");
} catch (AgeException e) {
System.out.println(e.getMessage());
}
}
}
```
注:以上代码仅供参考,具体实现方式可能因人而异。
阅读全文