Let's Think This Through
This is the final part of the project. We'll use exception handling so that when invalid data comes in (say, a score outside the 0-100 range), the program handles it gracefully instead of crashing. We'll build a custom exception class, InvalidScoreException, extending Exception. We'll also use the Comparator interface to sort the student list by average score. Finally, we'll print a summary table report of all the student data and wrap up the project.
Let's Build It
Extend Exception with an InvalidScoreException class, calling super(message) in its constructor. In the StudentManager class, write an addScoreSafe(Student s, String subject, int score) method that throws InvalidScoreException when the score is outside 0-100 — don't forget to add throws InvalidScoreException to the method signature. In printReport(), use students.sort() with Comparator.comparingDouble(Student::calculateAverage).reversed() to sort so the highest average comes first, then print a formatted table with System.out.printf(). In the main method, try calling addScoreSafe() inside a try-catch block with an invalid score and see the error message get caught.
Sample Code
import java.util.ArrayList;
import java.util.Comparator;
class InvalidScoreException extends Exception {
public InvalidScoreException(String message) {
super(message);
}
}
class StudentManager {
private ArrayList<Student> students = new ArrayList<>();
public void addStudent(Student s) {
students.add(s);
}
public void addScoreSafe(Student s, String subject, int score) throws InvalidScoreException {
if (score < 0 || score > 100) {
throw new InvalidScoreException(subject + " score must be 0-100, got: " + score);
}
s.addScore(subject, score);
}
public void printReport() {
students.sort(Comparator.comparingDouble(Student::calculateAverage).reversed());
System.out.println("---- Final Report ----");
for (Student s : students) {
System.out.printf("%-10s Avg: %.1f Grade: %s%n",
s.getName(), s.calculateAverage(), s.getGrade());
}
}
}
public class StudentApp {
public static void main(String[] args) {
StudentManager manager = new StudentManager();
Student s1 = new Student("Aung Aung", 101);
Student s2 = new Student("Su Su", 102);
manager.addStudent(s1);
manager.addStudent(s2);
try {
manager.addScoreSafe(s1, "Math", 95);
manager.addScoreSafe(s2, "Math", 120); // invalid
} catch (InvalidScoreException e) {
System.out.println("Error: " + e.getMessage());
}
manager.printReport();
}
}The console will print an error message like Error: Math score must be 0-100, got: 120, then print the student list sorted by average descending as a Final Report table.5-Minute Try-It
On top of InvalidScoreException, build an InvalidNameException custom exception that throws when a student name is an empty string, and integrate it within 5 minutes.
A Quick Word of Caution
Remember that custom exceptions extending Exception are checked exceptions, so the caller side needs a try-catch or a throws declaration.