Thuta Learning
Java
ProjectsProgrammingBeginner

Student Manager Project - Part 3: Exceptions & Final Report

JavaLesson 3440 min

What you'll walk away with

  • Write InvalidScoreException and StudentNotFoundException by extending Exception
  • Explain how a throws clause becomes part of a method's contract and forces callers to react
  • Put a try-catch around each input line so one bad line cannot stop the whole batch
  • Sort a copy with Comparator.comparingDouble(...).reversed().thenComparing(...) and print a printf table

Explain it simply

Explain it simply

After exams, teachers send the office a big stack of mark sheets. Most are fine, but a few contain an impossible mark like "120", a student number that does not exist, or handwriting nobody can read. A clerk who throws away the whole stack because of one bad sheet is not much help. The right move is to set the bad sheet aside with a note saying why, and keep entering the rest.

In Java, "set it aside with a note" means throwing an exception and catching it. Part 3 adds that mechanism and finishes with a report sorted from the highest average down.

Problem → Why → Solution

The problem: one bad line wipes out the lines after it

The first draft wraps the entire for loop in one try block. When line 9, "102,Math,120", throws an InvalidScoreException, control jumps to the catch outside the loop. One error message appears, but lines 10 to 13 are never read. Line 13 was a perfectly valid correction of Ko Ko's Math to 61, and it is silently lost.

Even with line 9 fixed, line 11, "abc", is worse. Integer.parseInt() throws a NumberFormatException, this catch only handles InvalidScoreException, and the whole program can die with a stack trace. The same issue shows up on a smaller scale whenever two addScoreSafe() calls share one try: a failure in the first skips the second.

Draft.java
try {
    for (String line : lines) {
        String[] p = line.split(",");
        manager.recordScore(Integer.parseInt(p[0]), p[1], Integer.parseInt(p[2]));
    }
} catch (InvalidScoreException e) {           // first bad score ends the loop
    System.out.println("Error: " + e.getMessage());
}                                             // "abc" -> NumberFormatException escapes

Why are the remaining lines lost?

When an exception is thrown, Java abandons the current statement at once and searches outward for the nearest matching catch. If that catch sits outside the loop, the loop is exited and never re-entered. The scope of a try block decides how much work you give up when something fails. To give up on one record at a time, the try must be inside the loop.

Core concept: exceptions carry a broken rule back to the caller

Part 2's addScore() accepted any score. Part 3 adds the rule "scores run from 0 to 100". But the Student class should not print to the console or know about line numbers. So the place that checks the rule and the place that tells the user are kept apart, and an exception carries the message between them.

1. Write your own exception classes

InvalidScoreException extends Exception and its constructor only calls super(message). The class name itself says what went wrong, so catch blocks can handle each kind of error separately. StudentNotFoundException takes the id and builds its own message.

2. Check the rule next to the data

The range check now lives inside Student.addScore(), so no path that adds a score can skip it. That is exactly why Part 2 only handed out an unmodifiable view from getScores().

3. throws is part of the contract

A method that throws a checked exception (one that extends Exception) must declare it with throws. Every caller must then either catch it or declare throws itself. The moment addScore() changes, the compiler flags every caller that does not handle it yet.

4. One try per record

With the try inside the loop, a bad line is rejected on its own and the loop moves on. A multi-catch (A | B) handles two exception types that need the same response. NumberFormatException is unchecked, so the compiler never demands it, but input can always be malformed, so we catch it anyway.

ExceptionChecked?In this project
InvalidScoreExceptionChecked (extends Exception)Score outside 0-100
StudentNotFoundExceptionChecked (extends Exception)Unknown id
NumberFormatExceptionUnchecked (RuntimeException)Parsing "abc"
IllegalArgumentExceptionUnchecked (RuntimeException)Part 1 constructor checks
Mental model: read, check, reject or keep
  1. Split the line into three fields
  2. Parse the numbers
  3. recordScore() throws on a broken rule
  4. catch rejects the line, loop goes on
  5. Sort a copy and print the report

Size each try block to the amount of work you are willing to lose when one thing fails.

General pattern

java
class DomainException extends Exception {
    DomainException(String message) { super(message); }
}

void apply(Input in) throws DomainException {
    if (!valid(in)) throw new DomainException("why it failed: " + in);
}

for (Input in : batch) {
    try { apply(in); ok++; }
    catch (DomainException | NumberFormatException e) { report(in, e); }
}

The method throws when a rule is broken and declares it with throws. The batch loop wraps each item in its own try, reports failures, and keeps going.

Part 3 code: loading input and printing the Final Report

This example keeps every class from Parts 1 and 2 and only touches the places marked "NEW" and "CHANGED". The Student class must stay in the file too, or nothing compiles. printReport() sorts a copy rather than the manager's real list, so printing a report never changes the order everyone else sees. It uses a lines array instead of keyboard input (Scanner), so every run prints the same output. Notice that the correction on line 13 still gets in, even though lines 9-12 were bad.

StudentApp.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class StudentApp {
    public static void main(String[] args) {
        StudentManager manager = new StudentManager();
        manager.addStudent(new Student("Aung Aung", 101));
        manager.addStudent(new Student("Su Su", 102));
        manager.addStudent(new Student("Ko Ko", 103));
        manager.addStudent(new Student("Mya Mya", 104));

        // Scripted input: one "id,subject,score" record per line.
        String[] lines = {
            "101,Math,95", "101,English,82", "101,Science,88",
            "102,Math,72", "102,English,91", "102,Science,67",
            "103,Math,45", "103,English,58",
            "102,Math,120",      // score out of range
            "105,Math,80",       // no such student
            "103,Science,abc",   // not a number
            "103,Math",          // missing field
            "103,Math,61",       // a valid correction
        };

        int accepted = 0;
        for (int i = 0; i < lines.length; i++) {
            String where = "Line " + (i + 1);
            String[] parts = lines[i].split(",");
            if (parts.length != 3) {
                System.out.println(where + " skipped: expected id,subject,score");
                continue;
            }
            try {
                int id = Integer.parseInt(parts[0].strip());
                int score = Integer.parseInt(parts[2].strip());
                manager.recordScore(id, parts[1].strip(), score);
                accepted++;
            } catch (InvalidScoreException | StudentNotFoundException e) {
                System.out.println(where + " rejected: " + e.getMessage());
            } catch (NumberFormatException e) {
                System.out.println(where + " rejected: not a number");
            }
        }
        System.out.println("Accepted " + accepted + " of " + lines.length + " lines");
        System.out.println();
        manager.printReport();
    }
}

// NEW in Part 3: two checked exceptions for bad input ------------
class InvalidScoreException extends Exception {
    public InvalidScoreException(String message) {
        super(message);
    }
}

class StudentNotFoundException extends Exception {
    public StudentNotFoundException(int id) {
        super("no student with id " + id);
    }
}

class Student {
    private final String name;
    private final int id;
    private final Map<String, Integer> subjectScores;

    public Student(String name, int id) {
        if (name == null || name.isBlank()) {
            throw new IllegalArgumentException("name must not be blank");
        }
        if (id <= 0) {
            throw new IllegalArgumentException("id must be positive, got " + id);
        }
        this.name = name.strip();
        this.id = id;
        this.subjectScores = new LinkedHashMap<>();
    }

    public String getName() {
        return name;
    }

    public int getId() {
        return id;
    }

    // CHANGED in Part 3: the range rule now lives here, so no caller can skip it
    public void addScore(String subject, int score) throws InvalidScoreException {
        if (score < 0 || score > 100) {
            throw new InvalidScoreException(
                    subject + " score must be 0-100, got: " + score);
        }
        subjectScores.put(subject, score);
    }

    public Map<String, Integer> getScores() {
        return Collections.unmodifiableMap(subjectScores);
    }

    public double calculateAverage() {
        if (subjectScores.isEmpty()) {
            return 0.0;
        }
        int total = 0;
        for (int score : subjectScores.values()) {
            total += score;
        }
        return (double) total / subjectScores.size();
    }

    public String getGrade() {
        if (subjectScores.isEmpty()) {
            return "-";
        }
        double avg = calculateAverage();
        if (avg >= 90) {
            return "A";
        } else if (avg >= 75) {
            return "B";
        } else if (avg >= 50) {
            return "C";
        } else {
            return "F";
        }
    }
}

class StudentManager {
    private final List<Student> students = new ArrayList<>();

    public boolean addStudent(Student student) {
        if (findById(student.getId()) != null) {
            return false;
        }
        students.add(student);
        return true;
    }

    public Student findById(int id) {
        for (Student s : students) {
            if (s.getId() == id) {
                return s;
            }
        }
        return null;
    }

    // NEW in Part 3 ------------------------------------------------
    public void recordScore(int id, String subject, int score)
            throws InvalidScoreException, StudentNotFoundException {
        Student student = findById(id);
        if (student == null) {
            throw new StudentNotFoundException(id);
        }
        student.addScore(subject, score);
    }

    public void printReport() {
        List<Student> ranked = new ArrayList<>(students); // sort a copy
        ranked.sort(Comparator.comparingDouble(Student::calculateAverage).reversed()
                .thenComparing(Student::getName));

        System.out.println("---- Final Report ----");
        System.out.printf("%-10s %6s  %s%n", "Name", "Avg", "Grade");
        for (Student s : ranked) {
            if (s.getScores().isEmpty()) {
                System.out.printf("%-10s %6s  %s%n", s.getName(), "n/a", s.getGrade());
            } else {
                System.out.printf("%-10s %6.1f  %s%n",
                        s.getName(), s.calculateAverage(), s.getGrade());
            }
        }
    }
}

Code breakdown

  1. A checked exception of our ownclass InvalidScoreException extends Exception {

    Extending Exception makes it checked. Extending RuntimeException instead would make it unchecked, and the compiler would no longer force callers to deal with it.

  2. The rule moves into Studentpublic void addScore(String subject, int score) throws InvalidScoreException {

    With the range check here, 120 can never reach the map. Because of throws, recordScore() has to declare it in its own signature too.

  3. A try per linemanager.recordScore(id, parts[1].strip(), score);

    This call sits inside a try within the loop, so an exception skips accepted++, runs the catch, and the loop continues with the next line.

  4. Multi-catch} catch (InvalidScoreException | StudentNotFoundException e) {

    Two exception types with the same handling share one catch. getMessage() returns the message given when the exception was constructed.

  5. Sort a copy, highest firstranked.sort(Comparator.comparingDouble(Student::calculateAverage).reversed()

    comparingDouble sorts by average ascending and reversed() flips it to highest first. ranked is a copy, so the manager's own list keeps its order, and thenComparing(Student::getName) breaks ties by name.

You should see
Line 9 rejected: Math score must be 0-100, got: 120
Line 10 rejected: no student with id 105
Line 11 rejected: not a number
Line 12 skipped: expected id,subject,score
Accepted 9 of 13 lines

---- Final Report ----
Name          Avg  Grade
Aung Aung    88.3  B
Su Su        76.7  B
Ko Ko        59.5  C
Mya Mya       n/a  -
The path of one input line
  1. split(",") into fields
  2. Skip if there are not 3 fields
  3. parseInt() the id and score
  4. recordScore() → findById() → addScore()

Every rule passes

score stored, accepted++

An exception is thrown

Line N rejected: <message>

printf and the default locale

%-10s left-aligns the name in a 10-character column, and %6.1f right-aligns the number in 6 characters with one decimal place, which is why the columns line up.

One catch: printf and String.format use the machine's default locale. On a computer set to a German locale, 88.3 prints as 88,3. That is fine for a report a person reads, but for a file a program will read, such as CSV, pin the locale with String.format(Locale.ROOT, ...).

In real projects

In real projects

CSV import, bank statement upload and bulk mark upload all follow this pattern: validate each row, store the good ones, collect the bad ones with their row number and reason, and finish with a summary like "9 of 13 accepted". The user fixes only the four bad rows and uploads them again.

Some systems need "all or nothing" instead. In a batch of money transfers, one bad line must cancel the whole batch. Then you validate every row first and store nothing unless all of them pass. Which policy applies is a business decision, and the code should make it obvious. When the report is saved to a file, writing a temporary file first and replacing the real one with Files.move() protects the old file if the program crashes halfway through writing.

Common mistakes

Common mistakes

Forgetting throws in the signature

Writing throw new InvalidScoreException(...) in addScore() without declaring throws gives the compile error "unreported exception InvalidScoreException; must be caught or declared to be thrown". That is not a bug in Java; it is the whole point of a checked exception.

Wrapping the whole loop in one try

As the problem section showed, the first error exits the loop and every valid line after it is lost. If each item should be processed independently, put the try inside the loop body.

Catching plain Exception for everything

catch (Exception e) also swallows real bugs in your own code, such as a NullPointerException, and reports them as "bad input". Catch only the exception types you actually expect, by name.

Sorting the manager's real list

Calling students.sort(...) directly inside printReport() reorders the roster just because someone printed a report, a surprising side effect for a print method. Copy with new ArrayList<>(students) and sort the copy.

Mini challenge

Export the report as a CSV file

Write exportCsv(List<ReportRow> rows, Path file). It writes a header line and one line per row in UTF-8, closing the writer with try-with-resources. main creates a temporary file, exports, reads the file back and prints it, then deletes the file.

  • exportCsv() declares throws IOException instead of catching it itself
  • Format the average with Locale.ROOT and one decimal place (88.3, never 88,3)
  • main catches IOException and deletes the temp file in a finally block
  • Do not print the temp file's path, because it changes on every run
ExportChallenge.java
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;

public class ExportChallenge {
    static void exportCsv(List<ReportRow> rows, Path file) throws IOException {
        // TODO: try (BufferedWriter out = Files.newBufferedWriter(file, UTF_8)) {
        //   header "id,name,average,grade", then one line per row
        // }
    }

    public static void main(String[] args) {
        // TODO: build three rows, create a temp file, export, read back, print,
        // and delete the file in finally
    }
}

record ReportRow(int id, String name, double average) {
    String grade() { /* TODO: same thresholds as Part 2 */ return "?"; }
}

Expected: "Wrote 4 lines:" followed by the header and three rows: 101,Aung Aung,88.3,B / 102,Su Su,76.7,B / 103,Ko Ko,59.5,C.

Show hint

Files.createTempFile("report", ".csv") creates an empty file for you; read it back with Files.readAllLines(file, StandardCharsets.UTF_8). A record's fields are read through the methods id(), name() and average().

Show solution
ExportChallenge.java
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Locale;

public class ExportChallenge {
    static void exportCsv(List<ReportRow> students, Path file) throws IOException {
        try (BufferedWriter out = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
            out.write("id,name,average,grade");
            out.newLine();
            for (ReportRow s : students) {
                out.write(String.format(Locale.ROOT, "%d,%s,%.1f,%s",
                        s.id(), s.name(), s.average(), s.grade()));
                out.newLine();
            }
        } // the writer is flushed and closed here, even if write() throws
    }

    public static void main(String[] args) {
        List<ReportRow> students = List.of(
                new ReportRow(101, "Aung Aung", 88.33),
                new ReportRow(102, "Su Su", 76.67),
                new ReportRow(103, "Ko Ko", 59.5));
        Path file = null;
        try {
            file = Files.createTempFile("report", ".csv");
            exportCsv(students, file);
            List<String> lines = Files.readAllLines(file, StandardCharsets.UTF_8);
            System.out.println("Wrote " + lines.size() + " lines:");
            lines.forEach(System.out::println);
        } catch (IOException e) {
            System.out.println("Export failed: " + e.getMessage());
        } finally {
            if (file != null) {
                try {
                    Files.deleteIfExists(file);
                } catch (IOException ignored) {
                    // nothing useful to do if cleanup fails
                }
            }
        }
    }
}

record ReportRow(int id, String name, double average) {
    String grade() {
        if (average >= 90) return "A";
        if (average >= 75) return "B";
        if (average >= 50) return "C";
        return "F";
    }
}

Quick quiz 1 / 3

What changes if you declare class InvalidScoreException extends RuntimeException instead?

Quick quiz 2 / 3

If the try block wraps the entire for loop and line 9 throws InvalidScoreException, what happens to the correction on line 13?

Quick quiz 3 / 3

Averages are 88.3, 76.7 and 59.5. Sorting with Comparator.comparingDouble(Student::calculateAverage) and no reversed(), who comes first?

What to remember

  • A custom checked exception just extends Exception and calls super(message)
  • Check rules next to the data (Student.addScore()) and announce them with throws
  • A try around each item means one bad line cannot stop the batch
  • Sort a copy for the report, using reversed() and thenComparing()

Java Language Specification, Java SE 25 — Oracle

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Student Manager Project - Part 3: Exceptions & Final Report | Thuta Learning