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



我需要找到大学里所有学生的平均成绩,并在Arrays.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
);

以及获得平均值的方法:

double warCraftAverageGrade = students.stream()
.mapToDouble(Student::getWarCraftGrade)
.average()
.getAsDouble();

我创建了特殊的异常类:

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");
}
}

}当我尝试使用StudentActions.range()方法时出现问题:

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)");
}

在这种情况下,形成自定义异常的正确解决方案是什么?例如,如果等级为负,则正确的代码必须抛出GradeException

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

提前谢谢!

最好将异常移动到构造函数中,而不是每次获得平均值时都必须捕获异常。只需使其不能构造无效对象。在您的特定情况下,抛出已检查异常(一个不扩展RuntimeException并附加到throws子句的异常,迫使调用方处理它(是没有意义的。

这个答案表明什么时候使用已检查的异常(强调我的(是合适的:

我还认为抛出检查异常是可以的1,假设检查异常是1(声明的,2(特定于您报告的问题,3(对于这个2来说,期望调用者处理检查异常是合理的

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


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

最后一件事:我会让你的方法成为非静态的,因为你在处理一个实例。在Java中(我不知道你来自哪种语言(,当前实例this在所有非静态方法中都可用,并且比将实例传递到静态方法更受欢迎。


看看这些问题:

  • 何时抛出异常
  • 让构造函数抛出异常是一种好的做法吗

最新更新