LearnFrenzy
Sign in Take a free test

Exception Handling · Exception Handling Programs · Question 2

CSV import with a per-line error report in Java Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

Import student rows "roll,name,marks" from text; validate each line with a custom exception that carries the line number, keep the good rows, and print an error report.

Solution
Main.java
import java.util.ArrayList;
import java.util.List;

class RowException extends Exception {
    private static final long serialVersionUID = 1L;
    RowException(int line, String problem) { super("line " + line + ": " + problem); }
}

record Student(int roll, String name, int marks) { }

public class Main {
    static Student parse(int line, String row) throws RowException {
        String[] f = row.split(",");
        if (f.length != 3) throw new RowException(line, "expected 3 fields, found " + f.length);
        int roll, marks;
        try {
            roll = Integer.parseInt(f[0].strip());
            marks = Integer.parseInt(f[2].strip());
        } catch (NumberFormatException e) {
            throw new RowException(line, "roll and marks must be numbers");
        }
        if (f[1].isBlank()) throw new RowException(line, "name is empty");
        if (marks < 0 || marks > 100) throw new RowException(line, "marks out of range: " + marks);
        return new Student(roll, f[1].strip(), marks);
    }

    public static void main(String[] args) {
        String csv = """
            1,Asha,91
            2,Ravi,abc
            3,,70
            4,Meena,84
            5,John
            6,Zoya,105
            """;
        List<Student> ok = new ArrayList<>();
        List<String> errors = new ArrayList<>();
        String[] lines = csv.strip().split("\n");
        for (int i = 0; i < lines.length; i++) {
            try {
                ok.add(parse(i + 1, lines[i]));
            } catch (RowException e) {
                errors.add(e.getMessage());
            }
        }
        System.out.println("imported " + ok.size() + ": " + ok.stream().map(Student::name).toList());
        errors.forEach(e -> System.out.println("  " + e));
    }
}

Output Verified by compiling and running

imported 2: [Asha, Meena]
  line 2: roll and marks must be numbers
  line 3: name is empty
  line 5: expected 3 fields, found 2
  line 6: marks out of range: 105

A checked custom exception forces the caller to deal with bad rows; one bad line never stops the whole import.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links