自定义异常类
问题:
请使用代码实现
每一个学生(Student)都有学号,姓名和分数,分数永远不能为负数
如果老师给学生赋值一个负数,抛出一个自定异常
public class NoScoreException extends RuntimeException {
public NoScoreException() {
}
public NoScoreException(String message) {
super(message);
}
}
public class Student {
// private int number;
private String name;
private int grade;
public Student() {
}
public Student(String name, int grade) {
this.name = name;
this.grade = grade;
if (grade < 0) {
throw new NoScoreException("分数不能为负数" + grade);
}
this.score(grade);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
public void score(int score){
if (score < 0) {
throw new NoScoreException("分数不能为负数" + score);
}
this.score(score);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return grade == student.grade &&
Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, grade);
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", grade=" + grade +
'}';
}
}
public class Test {
public static void main(String[] args) {
Student student1 = new Student("张三",-8);
// student1.score(-58);
}
}