简体   繁体   English

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

[英]Creating Custom Exception while calculating the average in the Arrays.asList

I need find the average grade of all the students in the university and create custom exception while finding the average in the Arrays.asList .我需要找到大学中所有学生的平均成绩并创建自定义异常,同时在Arrays.asList中找到平均值。 Exception should be thrown if int warCraftGrade < 0 or int warCraftGrade > 10. I have the following code:如果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;
}

I have the list of students:我有学生名单:

static List<Student> students = Arrays.asList(
    new Student("Geoffrey Baratheon", 8),
    new Student("Barristan Selmy", 6) //and so on
);

And the method of getting the average:以及获取平均值的方法:

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

I created special exception class:我创建了特殊异常 class:

public class GradeException extends Exception{
public GradeException() {
}
public GradeException(String message) {
    super(message);
}
public GradeException(String message, Throwable cause) {
    super(message, cause);
}

And the class to define the exception method:和 class 来定义异常方法:

public class StudentActions {
public static void range (Student student) throws GradeException {
    if (student.warCraftGrade < 0 || student.warCraftGrade > 10) {
        throw new GradeException("Wrong grade");
    }
}

} The problem occurs when I'm trying to use StudentActions.range() method:当我尝试使用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)");
    }

What is the correct solution to form the custom exception in such a case?在这种情况下形成自定义异常的正确解决方案是什么? The correct code must throw GradeException if the grade, for example, is negative:例如,如果成绩为负数,则正确的代码必须抛出GradeException

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

Thank you in advance!先感谢您!

It would be better to move the exception into the constructor instead of having to catch an exception every time you get the average.最好将异常移动到构造函数中,而不是每次获得平均值时都必须捕获异常。 Simply make it so that you cannot construct an invalid object.简单地做,这样你就不能构造一个无效的 object。 And in your particular case, it does not make sense to throw a checked exception (an exception that does not extend a RuntimeException and is appended to the throws clause, forcing the caller to deal with it).在您的特定情况下,抛出已检查异常(不扩展RuntimeException并附加到throws子句的异常,强制调用者处理它)是没有意义的。

This answer suggests when it is appropriate to use checked exceptions (emphasis mine):这个答案表明何时适合使用检查的异常(强调我的):

I also think that throwing checked exceptions can be OK 1 , assuming that the checked exception is 1) declared, 2) specific to the problem you are reporting, and 3) it is reasonable to expect the caller to deal with a checked exception for this 2 .我还认为抛出检查异常可以是 OK 1 ,假设检查异常是 1) 声明的,2) 特定于您报告的问题,以及 3)期望调用者为此处理检查异常是合理的2 .

2 - For example, the existing FileInputStream constructors will throw FileNotFoundException if you try to open a file that does not exist. 2 - 例如,如果您尝试打开不存在的文件,现有的 FileInputStream 构造函数将抛出 FileNotFoundException。 Assuming that it is reasonable for FileNotFoundException to be a checked exception 3 , then the constructor is the most appropriate place for that exception to be thrown.假设 FileNotFoundException 是一个经过检查的异常3是合理的,那么构造函数是引发该异常的最合适的位置。 If we threw the FileNotFoundException the first time that (say) a read or write call was made, that is liable to make application logic more complicated .如果我们在第一次(比如)进行读取或写入调用时抛出 FileNotFoundException,这可能会使应用程序逻辑更加复杂


Also, I would recommend moving the actual grade range logic into a method, rather than forcing the caller to do it every time.另外,我建议将实际的成绩范围逻辑移动到一个方法中,而不是每次都强制调用者这样做。

One last thing: I'd make your methods nonstatic since you're dealing with an instance.最后一件事:我会让你的方法成为非静态的,因为你正在处理一个实例。 In Java (I don't know what language you're coming from), this , the current instance, is available in all nonstatic methods and is favored over passing an instance into a static method.在 Java (我不知道您来自什么语言)中,当前实例this可用于所有非静态方法,并且优于将实例传递给 static 方法。


Take a look at these questions:看看这些问题:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM