Java类构造器校验非法测试成绩时未抛出第二次异常问题咨询
核心问题原因
你传入的成绩数组第一个元素就是-1,for循环执行到index=0时就会触发非法成绩判断逻辑,直接抛出InvalidScore异常,构造器会立刻终止执行,后续索引为4的101.0根本没有机会被遍历校验,因此你看不到第二个异常的提示信息。
现有代码的其他问题
- 第二个
if判断存在语法错误:你写的if (scores[index >= 0 && scores[index] <= 100)括号位置错误,正确写法应为if (scores[index] >= 0 && scores[index] <= 100)。同时该判断逻辑完全冗余,因为前面已经对成绩范围做了校验,超出范围的情况已经抛出异常终止执行,能走到该分支的成绩必然是合法值,无需二次判断。 - 如果你需要检测出数组中所有的非法成绩再统一抛出提示,而不是遇到第一个非法值就终止校验,就不能在遍历过程中碰到非法值立刻抛异常。
修复代码示例(全量校验非法成绩)
public Test(double[] scores) throws InvalidScore { testScores = new double[scores.length]; // 存储所有非法成绩的提示信息 List<String> invalidMsgList = new ArrayList<>(); for (int index = 0; index < scores.length; index++) { if (scores[index] < 0 || scores[index] > 100) { invalidMsgList.add(String.format("Element: %d Invalid score: %.1f", index, scores[index])); continue; } testScores[index] = scores[index]; } // 遍历完成后判断是否存在非法成绩,统一抛出异常 if (!invalidMsgList.isEmpty()) { throw new InvalidScore(String.join("\n", invalidMsgList)); } }
内容的提问来源于stack exchange,提问作者C L A R K
相关产品推荐
相关产品推荐

