Skip to lesson

Skip and report bad rows

Real data files always have a few bad rows: a missing name, marks typed as 9O with a letter O, a roll number of -3. A good import keeps the good rows, sets the bad ones aside with the exact line and reason, and tells a person what to fix.

Validating each field

Validation means checking that a value makes sense before you use it. Parsing asks can this text become an int?; validation also asks is this int a sensible roll number or mark?

An import: the lines of students.csv go into a parse-and-validate step. Good rows become Student objects in a list. Bad rows, such as a row with missing marks, are kept with their line number for an error report, so one bad row does not stop the import.

Example 1 · Collect every problem in a row

FieldValidationDemo.javaJava
import java.util.ArrayList;import java.util.List;
public class FieldValidationDemo {    static List<String> problems(String[] f) {        List<String> p = new ArrayList<>();        if (f.length != 3) {            p.add("expected 3 fields but got " + f.length);            return p;        }        String roll = f[0].trim();        String name = f[1].trim();        String marks = f[2].trim();        if (!roll.matches("\\d+")) {            p.add("roll '" + roll + "' is not a whole number");        }        if (name.isEmpty()) {            p.add("name is empty");        }        if (!marks.matches("\\d+")) {            p.add("marks '" + marks + "' is not a whole number");        } else if (Integer.parseInt(marks) > 100) {            p.add("marks " + marks + " is more than 100");        }        return p;    }
    public static void main(String[] args) {        String[] rows = {"101,Asha,87", "10a,,105", "103,Chitra,9O", "104,Dev"};        for (String row : rows) {            List<String> p = problems(row.split(",", -1));            if (p.isEmpty()) {                System.out.println("OK    " + row);            } else {                System.out.println("BAD   " + row + " -> " + String.join("; ", p));            }        }    }}
Output
OK    101,Asha,87
BAD   10a,,105 -> roll '10a' is not a whole number; name is empty; marks 105 is more than 100
BAD   103,Chitra,9O -> marks '9O' is not a whole number
BAD   104,Dev -> expected 3 fields but got 2

What this code does

  • problems returns an empty list for a good row and one reason per problem for a bad row. The row 10a,,105 has three problems, and all three are reported at once.
  • 9O ends with the letter O, not zero. The reason shows the value in quotes, so the mistake is easy to spot. A wrong field count stops the checks early, because the other fields cannot be trusted.

Check every field and collect all the problems in a row into a list, instead of stopping at the first one. A clerk fixing the file then sees name is empty and marks 105 is more than 100 together, and fixes the row in one go. Write each reason in plain words with the bad value in quotes: marks '9O' is not a whole number. The quotes show hidden spaces and letters that look like digits.

text.matches("\\d+") is true when the text is one or more digits and nothing else. It is a regular expression, a small pattern language for text.

A RowError record with line number and reason

record RowError(int line, String reason, String text) holds everything a person needs to fix one bad row: where it is, what is wrong, and the row itself.

Example 2 · RowError and ImportResult: keep going after a bad row

RowErrorDemo.javaJava
import java.util.ArrayList;import java.util.List;
record Student(int roll, String name, int marks) {}
record RowError(int line, String reason, String text) {}
record ImportResult(List<Student> students, List<RowError> errors) {}
public class RowErrorDemo {    static List<String> problems(String[] f) {        List<String> p = new ArrayList<>();        if (f.length != 3) {            p.add("expected 3 fields but got " + f.length);            return p;        }        String roll = f[0].trim();        String name = f[1].trim();        String marks = f[2].trim();        if (!roll.matches("\\d+")) {            p.add("roll '" + roll + "' is not a whole number");        }        if (name.isEmpty()) {            p.add("name is empty");        }        if (!marks.matches("\\d+")) {            p.add("marks '" + marks + "' is not a whole number");        } else if (Integer.parseInt(marks) > 100) {            p.add("marks " + marks + " is more than 100");        }        return p;    }
    static ImportResult importLines(List<String> lines) {        List<Student> students = new ArrayList<>();        List<RowError> errors = new ArrayList<>();        for (int i = 1; i < lines.size(); i++) {        // index 0 is the header            int lineNo = i + 1;            String text = lines.get(i);            if (text.isBlank()) {                continue;            }            String[] f = text.split(",", -1);            List<String> p = problems(f);            if (p.isEmpty()) {                students.add(new Student(Integer.parseInt(f[0].trim()), f[1].trim(), Integer.parseInt(f[2].trim())));            } else {                errors.add(new RowError(lineNo, String.join("; ", p), text));            }        }        return new ImportResult(students, errors);    }
    public static void main(String[] args) {        List<String> file = List.of("roll,name,marks", "101,Asha,87", "102,,64", "103,Chitra,92",                "", "104,Dev,105", "105,Esha,78");        ImportResult r = importLines(file);        System.out.println("Imported " + r.students().size() + " students");        for (Student s : r.students()) {            System.out.println("  " + s);        }        System.out.println("Rejected " + r.errors().size() + " rows");        for (RowError e : r.errors()) {            System.out.println("  line " + e.line() + ": " + e.reason() + "  [" + e.text() + "]");        }    }}
Output
Imported 3 students
  Student[roll=101, name=Asha, marks=87]
  Student[roll=103, name=Chitra, marks=92]
  Student[roll=105, name=Esha, marks=78]
Rejected 2 rows
  line 3: name is empty  [102,,64]
  line 6: marks 105 is more than 100  [104,Dev,105]

What this code does

  • Every row ends up in exactly one list. The bad rows on lines 3 and 6 do not stop the loop, so Chitra and Esha after them are still imported.
  • The line number is i + 1, because list index 0 is file line 1. The blank line 5 is skipped but still counted, so line 6 matches what an editor shows.

The import loop now never throws for a bad row. It catches or checks each row, adds good rows to one list and a RowError to another, and moves on. At the end it returns both lists together in an ImportResult record. The caller decides what to do with the result: save the good rows, show the errors, or both. The import code itself stays free of printing and saving.

Continue or stop: an error limit

Skipping bad rows is right when a few rows are broken. But if someone uploads the attendance file instead of the marks file, every row is bad, and a report with 5,000 errors helps nobody.

Example 3 · An error limit for the wrong file

ErrorLimitDemo.javaJava
import java.util.ArrayList;import java.util.List;
record RowError(int line, String reason, String text) {}
public class ErrorLimitDemo {    static final int MAX_ERRORS = 3;
    static List<String> problems(String[] f) {        List<String> p = new ArrayList<>();        if (f.length != 3) {            p.add("expected 3 fields but got " + f.length);            return p;        }        String roll = f[0].trim();        String name = f[1].trim();        String marks = f[2].trim();        if (!roll.matches("\\d+")) {            p.add("roll '" + roll + "' is not a whole number");        }        if (name.isEmpty()) {            p.add("name is empty");        }        if (!marks.matches("\\d+")) {            p.add("marks '" + marks + "' is not a whole number");        } else if (Integer.parseInt(marks) > 100) {            p.add("marks " + marks + " is more than 100");        }        return p;    }
    static List<RowError> validateAll(List<String> lines) {        List<RowError> errors = new ArrayList<>();        for (int i = 1; i < lines.size(); i++) {            List<String> p = problems(lines.get(i).split(",", -1));            if (!p.isEmpty()) {                errors.add(new RowError(i + 1, String.join("; ", p), lines.get(i)));                if (errors.size() > MAX_ERRORS) {                    throw new IllegalStateException("Stopped at line " + (i + 1) + ": more than "                            + MAX_ERRORS + " bad rows. Is this the right file?");                }            }        }        return errors;    }
    public static void main(String[] args) {        List<String> marks = List.of("roll,name,marks", "101,Asha,87", "102,,64", "103,Chitra,92");        System.out.println("Marks file: " + validateAll(marks).size() + " bad row(s)");
        List<String> attendance = List.of("date,roll,status", "02-08-2024,101,P", "02-08-2024,102,A",                "02-08-2024,103,P", "02-08-2024,104,P", "02-08-2024,105,A", "02-08-2024,106,P");        try {            validateAll(attendance);        } catch (IllegalStateException e) {            System.out.println("Attendance file: " + e.getMessage());        }    }}
Output
Marks file: 1 bad row(s)
Attendance file: Stopped at line 5: more than 3 bad rows. Is this the right file?

What this code does

  • The marks file has one bad row, which is under the limit, so the import goes on as normal.
  • In the attendance file every row is bad. On the fourth error (line 5) the limit is passed and one clear message replaces what would have been a long, useless error list.

An error limit solves this. After, say, 10 errors, the import stops with one message: Too many bad rows, is this the right file? The limit is a constant you choose for each kind of file. Also decide whether a partial import is allowed. Marks for a report card should be all or nothing: if any row is bad, save nothing and ask for a fixed file. A list of fest registrations can usually be saved in part.

Writing an error report file

An error report is a small text file that lists every bad row with its line number and reason, plus a summary line such as Rows read: 6, imported: 4, rejected: 2. You can email it to the person who made the file.

Example 4 · Import a file and write marks-errors.txt

ErrorReportDemo.javaJava
import java.io.BufferedReader;import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;import java.util.ArrayList;import java.util.List;
record Student(int roll, String name, int marks) {}
record RowError(int line, String reason, String text) {}
public class ErrorReportDemo {    static List<String> problems(String[] f) {        List<String> p = new ArrayList<>();        if (f.length != 3) {            p.add("expected 3 fields but got " + f.length);            return p;        }        String roll = f[0].trim();        String name = f[1].trim();        String marks = f[2].trim();        if (!roll.matches("\\d+")) {            p.add("roll '" + roll + "' is not a whole number");        }        if (name.isEmpty()) {            p.add("name is empty");        }        if (!marks.matches("\\d+")) {            p.add("marks '" + marks + "' is not a whole number");        } else if (Integer.parseInt(marks) > 100) {            p.add("marks " + marks + " is more than 100");        }        return p;    }
    public static void main(String[] args) throws IOException {        Path input = Path.of("marks.csv");        Files.writeString(input, "roll,name,marks\n101,Asha,87\n102,,64\n103,Chitra,92\n104,Dev,1O5\n105,Esha,78\n",                StandardCharsets.UTF_8);
        List<Student> students = new ArrayList<>();        List<RowError> errors = new ArrayList<>();        int rowsRead = 0;        try (BufferedReader in = Files.newBufferedReader(input, StandardCharsets.UTF_8)) {            String line = in.readLine();            int lineNo = 1;            while ((line = in.readLine()) != null) {                lineNo++;                if (line.isBlank()) {                    continue;                }                rowsRead++;                String[] f = line.split(",", -1);                List<String> p = problems(f);                if (p.isEmpty()) {                    students.add(new Student(Integer.parseInt(f[0].trim()), f[1].trim(), Integer.parseInt(f[2].trim())));                } else {                    errors.add(new RowError(lineNo, String.join("; ", p), line));                }            }        }
        List<String> report = new ArrayList<>();        report.add("Import report for " + input.getFileName());        report.add("Rows read: " + rowsRead + ", imported: " + students.size() + ", rejected: " + errors.size());        for (RowError e : errors) {            report.add("line " + e.line() + ": " + e.reason() + " | " + e.text());        }        Path reportFile = Path.of("marks-errors.txt");        Files.write(reportFile, report, StandardCharsets.UTF_8);
        System.out.println("Wrote " + reportFile.getFileName() + ":");        for (String line : Files.readAllLines(reportFile, StandardCharsets.UTF_8)) {            System.out.println("  " + line);        }        Files.deleteIfExists(input);        Files.deleteIfExists(reportFile);    }}
Output
Wrote marks-errors.txt:
  Import report for marks.csv
  Rows read: 5, imported: 3, rejected: 2
  line 3: name is empty | 102,,64
  line 5: marks '1O5' is not a whole number | 104,Dev,1O5

What this code does

  • The loop from the Read a whole CSV file lesson now collects errors instead of throwing. rowsRead counts only real rows, so the summary adds up: 5 read, 3 imported, 2 rejected.
  • Files.write saves the report lines with UTF-8. The program reads the report back only to show it here; in real use you would send the file to the person who made marks.csv.

Build the report as a List<String> and save it with Files.write(path, lines, StandardCharsets.UTF_8). Name it after the input, for example marks-errors.txt, so it is easy to match the two. Keep the report for people: one line per error, in file order, the line number first. If a program will read the errors, write them as CSV instead; the next lesson shows how to quote such values.

Order of execution

Order of an import with a report

Put the steps of the import in the order the program runs them.

Next step

Check your understanding

12 quick questions