Skip to content

Checkpoint: Recover per Line

The Course
•
25 min study

Importing several lines requires an explicit recovery policy. This checkpoint skips and reports invalid records while keeping valid ones, including valid records after a bad line. It does not promise a transaction that rolls back the entire batch. Choose one policy and test exactly that policy.

Work through the example

The catch belongs inside the loop when one bad line should not cancel later lines. A catch outside would stop the loop at the first rejection. Accepted count changes only after parsing succeeds. Do not replace a rejected value with zero and then count it as a successful import.

Before Run, write the output and identify the exact line responsible for each result. Each editor is a separate program; names and edits in one box do not carry into the next.

Predict, then run Java
public class Main {
    public static void main(String[] args) {
        int accepted = 0;
        for (String text : new String[] {"25", "nope", "10"}) {
            try {
                int minutes = Integer.parseInt(text);
                System.out.println(minutes);
                accepted++;
            } catch (NumberFormatException expected) {
                System.out.println("Rejected");
            }
        }
        System.out.println("Accepted: " + accepted);
    }
}
Check your prediction
Text
25
Rejected
10
Accepted: 2

Compare the behavior

Line numbers help a learner or user find a bad record. Blank lines still occupy a physical line number even when they are skipped. Keep the line counter separate from the accepted counter. They answer different questions.

Trace the changed case Java
public class Main {
    public static void main(String[] args) {
        String[] lines = {"Read", "", "Test"};
        for (int i = 0; i < lines.length; i++) {
            if (!lines[i].isEmpty()) {
                System.out.println("Line " + (i + 1) + ": " + lines[i]);
            }
        }
    }
}
Check your prediction
Text
Line 1: Read
Line 3: Test

Plan your acceptance cases

The brief for this checkpoint brings the whole day together: a reader, a checked exception and a recovery policy that reports instead of silently skipping.

Write importMinutes(BufferedReader reader). It reads every line, skips blank lines, and parses the rest as minutes from 1 through 240. It returns an Import object holding the total of accepted minutes and a list of problems, one per rejected line, written as line N: reason with the physical line number (blank lines count). Parsing lives in parseMinutes(String), which throws your own checked InvalidRecord exception with the reason not a whole number or outside 1-240. importMinutes does not open or close the reader: main owns it, opens it with try-with-resources, and turns an IOException into an IllegalStateException.

Predict each row before writing code:

Input linesTotalProblemsSkill it checks
25, bad, blank, 0, 1035line 2: not a whole number, line 4: outside 1-240The main case
bad, 1010line 1: not a whole numberA bad first line doesn't stop the rest
240, 241240line 2: outside 1-240Both ends of the range
no lines at all0noneEmpty input

When your version works, break it on purpose: count lineNumber only for nonblank lines. Which row shows the mistake?

Practice independently

Exercise

Checkpoint: Recover per Line

Implement the brief above and print the total followed by each problem. For the first row:

Text
Total: 35
line 2: not a whole number
line 4: outside 1-240
Your workspace Java
import java.io.BufferedReader;
import java.io.StringReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        String text = "25\nbad\n\n0\n 10 \n";
        System.out.println("Import the lines in text");
    }
}
Hint 1: the idea

There are three separate jobs. parseMinutes decides whether one line is valid and says why not. importMinutes walks the lines and decides what a rejection means (record it and keep going). main owns the reader and decides what a read failure means. Each catch belongs to the method that owns that decision.

Hint 2: a first step

Start with parseMinutes and InvalidRecord alone: call it on "25", "bad" and "0" from main and print each result or message. Then write the read loop from the Resources lesson, adding a lineNumber that increases on every line, blank or not, and a try/catch for InvalidRecord inside the loop.

Show one solution
Java
import java.io.BufferedReader;
import java.io.StringReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        String text = "25\nbad\n\n0\n 10 \n";
        try (BufferedReader reader = new BufferedReader(new StringReader(text))) {
            Import result = importMinutes(reader);
            System.out.println("Total: " + result.total());
            for (String problem : result.problems()) {
                System.out.println(problem);
            }
        } catch (IOException error) {
            throw new IllegalStateException("reading failed", error);
        }
    }

    static Import importMinutes(BufferedReader reader) throws IOException {
        Import result = new Import();
        int lineNumber = 0;
        String line = reader.readLine();
        while (line != null) {
            lineNumber++;
            if (!line.trim().isEmpty()) {
                try {
                    result.accept(parseMinutes(line));
                } catch (InvalidRecord error) {
                    result.reject("line " + lineNumber + ": " + error.getMessage());
                }
            }
            line = reader.readLine();
        }
        return result;
    }

    static int parseMinutes(String text) throws InvalidRecord {
        int value;
        try {
            value = Integer.parseInt(text.trim());
        } catch (NumberFormatException error) {
            throw new InvalidRecord("not a whole number");
        }
        if (value < 1 || value > 240) {
            throw new InvalidRecord("outside 1-240");
        }
        return value;
    }
}

final class InvalidRecord extends Exception {
    InvalidRecord(String message) {
        super(message);
    }
}

final class Import {
    private int total;
    private final List<String> problems = new ArrayList<>();

    void accept(int minutes) {
        total += minutes;
    }

    void reject(String problem) {
        problems.add(problem);
    }

    int total() {
        return total;
    }

    List<String> problems() {
        return new ArrayList<>(problems);
    }
}

Expected output:

Text
Total: 35
line 2: not a whole number
line 4: outside 1-240

The try/catch for InvalidRecord sits inside the loop, so a bad line costs only itself; the line number increases before the blank check, so line 4 is reported as line 4 even though line 3 was skipped. parseMinutes turns NumberFormatException into InvalidRecord, so the loop has one checked failure type to handle and cannot accidentally swallow unrelated errors. importMinutes declares throws IOException rather than catching it, because a broken reader is not a bad record: main, which opened the reader, decides that.

Change it and test again

Change the policy to "stop at the first bad record": what is the smallest change, and what does the first row print now? Restore it. Then add a check that result.problems().clear() does not empty the Import's own list.

Explain before moving on

Describe what happens to valid work before and after a bad record. Why is that a policy decision rather than something exceptions decide automatically?

Was this article helpful?

Your response is saved on this device.