1. 学生信息类异常 1)定义一个运行时异常 StudentException。 2)定义一个学生类 Student,含成员变量姓名 name,年龄 age,性别 sex.一个带三个参数的构造方法。 及一个成员方法 public void show(),用来显示学生信息。在方法 中,判断姓名字符数如果超出 5,抛出 StudentException 异常,消息 为"姓名不合法,太长"; age 如果小于 10 或大于 30,抛出 StudentException 异常,消息为" 年龄不合法,年龄必须为 10~30 之间" sex 如果不等于"男"或“女”,抛出 StudentException 异常,消息 为"性别不合法,性别只能为男或女" 3)定义一个 TestStudent 类,在 main 方法中定义几个 Student 实例, 并调用 show 方法;
时间: 2024-03-11 12:48:58 浏览: 12
根据您的要求,我编写了以下 Java 代码来实现:
```
public class StudentException extends RuntimeException {
public StudentException(String message) {
super(message);
}
}
public class Student {
private String name;
private int age;
private String sex;
public Student(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public void show() {
if (name.length() > 5) {
throw new StudentException("姓名不合法,太长");
}
if (age < 10 || age > 30) {
throw new StudentException("年龄不合法,年龄必须为 10~30 之间");
}
if (!sex.equals("男") && !sex.equals("女")) {
throw new StudentException("性别不合法,性别只能为男或女");
}
System.out.println("姓名:" + name + ",年龄:" + age + ",性别:" + sex);
}
}
public class TestStudent {
public static void main(String[] args) {
Student s1 = new Student("Tommy", 18, "男");
Student s2 = new Student("JerryMouse", 8, "男");
Student s3 = new Student("Lucy", 25, "女");
try {
s1.show();
s2.show();
s3.show();
} catch (StudentException e) {
e.printStackTrace();
}
}
}
```
在程序中,我们定义了一个运行时异常 `StudentException`,它继承自 `RuntimeException`,并在 `Student` 类中使用了该异常。在 `show` 方法中,我们按照要求对学生的信息进行了判断,如果不符合条件,就抛出对应的 `StudentException` 异常。在 `main` 方法中,我们创建了几个学生实例,并调用了它们的 `show` 方法,同时使用 try-catch 块捕获了可能抛出的 `StudentException` 异常并打印了异常栈信息。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)