ScoreException类
public class ScoreException extends Exception {
public ScoreException(String message) {
super(message);
}
// 默认构造函数,提供默认信息
public ScoreException() {
super("分数异常, 分数应该在0到200之间");
}
}
Studnet类
// 定义学生类Student
public class Student {
private String name;
private int age;
private double score;
// 构造方法
public Student(String name, int age, double score) throws ScoreException {
this.name = name;
this.age = age;
if (score < 0 || score > 200) {
throw new ScoreException();
}
this.score = score;
}
// getter和setter方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getScore() {
return score;
}
public void setScore(double score) throws ScoreException {
if (score < 0 || score > 200) {
throw new ScoreException();
}
this.score = score;
}
// print方法
public void print() {
System.out.println("姓名: " + name + ", 年龄: " + age + ", 分数: " + score);
}
}
Main类
// main方法
public class Main {
public static void main(String[] args) {
try {
// (1) 创建对象zhangsan,并捕获异常
Student zhangsan = new Student("张三", 20, 220);
} catch (ScoreException e) {
System.out.println(e.getMessage());
}
try {
// (2) 创建对象lisi,这里不会抛出异常
Student lisi = new Student("李四", 30, 120);
lisi.print(); // 打印信息
// (3) 调用lisi的setScore方法给score赋值230,并捕获异常
lisi.setScore(230);
} catch (ScoreException e) {
System.out.println(e.getMessage());
}
}
}