Java 在Arrays.asList中计算平均值时创建自定义异常

Java 在Arrays.asList中计算平均值时创建自定义异常,java,exception,try-catch,Java,Exception,Try Catch,我需要找到大学所有学生的平均成绩,并在数组中查找平均成绩时创建自定义异常。asList。如果int-warCraftGrade10,则应引发异常。我有以下代码: public class Student { String name; public final int warCraftGrade; public Student(String name, int warCraftGrade) { this.name = name; this.warCraftGrade = warC

我需要找到大学所有学生的平均成绩,并在
数组中查找平均成绩时创建自定义异常。asList
。如果
int-warCraftGrade
<0或
int-warCraftGrade
>10,则应引发异常。我有以下代码:

public class Student {
String name;
public final int warCraftGrade;

public Student(String name, int warCraftGrade) {
    this.name = name;
    this.warCraftGrade = warCraftGrade;
}
public String getName() {
    return name;
}
public int getWarCraftGrade() {
    return warCraftGrade;
}
我有学生名单:

static List<Student> students = Arrays.asList(
    new Student("Geoffrey Baratheon", 8),
    new Student("Barristan Selmy", 6) //and so on
);
我创建了特殊的异常类:

public class GradeException extends Exception{
public GradeException() {
}
public GradeException(String message) {
    super(message);
}
public GradeException(String message, Throwable cause) {
    super(message, cause);
}
以及定义异常方法的类:

public class StudentActions {
public static void range (Student student) throws GradeException {
    if (student.warCraftGrade < 0 || student.warCraftGrade > 10) {
        throw new GradeException("Wrong grade");
    }
}
在这种情况下,形成自定义异常的正确解决方案是什么?例如,如果成绩为负,则正确的代码必须抛出
GradeException

//new Student("Jorah Mormont", -8)

提前谢谢你

最好将异常移动到构造函数中,而不是每次获得平均值时都捕获异常。只需将其设置为不能构造无效对象。在您的特定情况下,抛出选中的异常(不扩展
RuntimeException
并附加到
throws
子句的异常,强制调用方处理该异常)是没有意义的

建议何时使用选中的异常(重点):

我还认为抛出检查过的异常是可行的,假设检查过的异常是1)声明的,2)特定于您报告的问题,以及3)期望调用方为此2处理检查过的异常是合理的

2-例如,如果您试图打开一个不存在的文件,现有的FileInputStream构造函数将抛出FileNotFoundException。假设FileNotFoundException是选中的异常3是合理的,那么构造函数是引发该异常的最合适位置。如果我们在第一次(比如)进行读或写调用时抛出FileNotFoundException,则可能会使应用程序逻辑更加复杂


此外,我建议将实际的等级范围逻辑移动到方法中,而不是每次都强制调用方这样做

最后一件事:由于您正在处理一个实例,所以我将使您的方法成为非静态的。在Java中(我不知道您来自哪种语言),
这个当前实例在所有非静态方法中都可用,并且优于将实例传递到静态方法


看看这些问题:


阅读以下内容:。感谢您的推荐!我按照您的建议,将异常移动到构造函数中,它就工作了。使用这种方法的唯一不利之处是,即使捕获到异常,当抛出异常时,进一步的代码执行也会停止。Java是我的第一门语言,我一个月前就开始学习它了。这就是一个例外的全部意义。。。它停止代码执行以处理错误
public static void main(String[] args) {
    try {
        StudentActions.range();
        double warCraftAverageGrade = students.stream()
                .mapToDouble(Student::getWarCraftGrade)
                .average()
                .getAsDouble();
        System.out.println("Average grade in WarCraft for the entire university = " + warCraftAverageGrade);
    } catch (GradeException e) {
        System.out.println("Grade is out of range (0-10)");
    }
//new Student("Jorah Mormont", -8)