Skip to content

Parsing & Validation

The Course
•
20 min study

External text has no Java type guarantee about its meaning. Parse the representation, then validate the domain value. A number can parse successfully and still be an invalid duration. Keep both checks at the boundary so the rest of the model can trust its inputs.

Work through the example

Integer.parseInt converts decimal text and throws NumberFormatException for malformed or out-of-range input. trim handles surrounding spaces. We reject null/blank input explicitly before conversion. The method then applies the 1–240 minute rule.

NumberFormatException is an IllegalArgumentException subtype, so a caller can catch the broader expected input-rejection category. Do not catch Exception around the entire application: a coding defect such as a null field should remain visible rather than be reported as “bad input.”

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) {
        System.out.println(parseMinutes(" 25 "));
        for (String text : new String[] {"nope", "0"}) {
            try {
                parseMinutes(text);
            } catch (IllegalArgumentException expected) {
                System.out.println("Rejected: " + text);
            }
        }
    }

    static int parseMinutes(String text) {
        if (text == null || text.trim().isEmpty()) {
            throw new IllegalArgumentException("minutes required");
        }
        int minutes = Integer.parseInt(text.trim());
        if (minutes < 1 || minutes > 240) {
            throw new IllegalArgumentException("minutes outside range");
        }
        return minutes;
    }
}
Check your prediction
Text
25
Rejected: nope
Rejected: 0

Compare the behavior

A simple delimited format is not general CSV. This course uses fields separated by semicolons and forbids semicolons inside fields. split(";", -1) preserves trailing empty fields; without -1, a missing last field could disappear. Check the field count before indexing to avoid an unrelated array exception.

Trace the changed case Java
public class Main {
    public static void main(String[] args) {
        String[] fields = "A1;Read;".split(";", -1);
        System.out.println(fields.length);
        System.out.println(fields[2].isEmpty());
        System.out.println("A1;Read;".split(";").length);
    }
}
Check your prediction
Text
3
true
2

Check shape, conversion and meaning separately

A four-field record has several independent ways to fail. A missing field is a shape error. A word where an integer belongs is a conversion error. The integer 0 can convert successfully and still fail the domain's positive-duration rule. One happy-path example does not challenge all three.

Check the number of fields before reading an index. Preserve trailing empty fields so the parser can distinguish a blank final value from an unrelated indexing failure. Normalize only the parts the format says may contain surrounding spaces; do not silently change identifiers or enum case unless that is a stated policy.

Keep parsing outside storage mutation. First construct a fully valid value, then ask the repository to add it. If parsing fails, there is no half-created stored record to clean up. The final importer will decide whether one rejected record stops a batch or permits later valid records to continue.

Practice independently

Exercise

Parsing & Validation: practice

Write parseTitle(String line) for exactly two fields id;title. Reject null, the wrong number of fields, and blank trimmed fields. Return the trimmed title. Print Read for " A1 ; Read ", then reject "A1;" and "A1;Read;extra" with a readable message.

Spend a few minutes on your own first. Compile after one small change, read the first error, and check the result against the requirements rather than matching the solution's layout.

Your workspace Java
public class Main {
    public static void main(String[] args) {
        System.out.println("Parse a deliberately small format");
    }
}
Hint 1: the idea

Do not index fields until the format's shape is known. Empty is different from missing.

Hint 2: a first step

Check fields.length first in a short-circuit OR condition, then test the trimmed values.

Show one solution

One possible implementation follows. Compare its decisions with yours: which values can change, what inputs are accepted, and what would expose a mistake?

Java
public class Main {
    public static void main(String[] args) {
        System.out.println(parseTitle(" A1 ; Read "));
        for (String line : new String[] {"A1;", "A1;Read;extra"}) {
            try {
                parseTitle(line);
            } catch (IllegalArgumentException error) {
                System.out.println(error.getMessage());
            }
        }
    }

    static String parseTitle(String line) {
        if (line == null) {
            throw new IllegalArgumentException("line required");
        }
        String[] fields = line.split(";", -1);
        if (fields.length != 2 || fields[0].trim().isEmpty() || fields[1].trim().isEmpty()) {
            throw new IllegalArgumentException("expected id;title");
        }
        return fields[1].trim();
    }
}

Expected output:

Text
Read
expected id;title
expected id;title

Change it and test again

Test an empty line, a blank ID and a title with surrounding spaces. State whether a title containing a semicolon can be represented. A parser must advertise its format limits instead of claiming to support CSV or arbitrary text.

Explain before moving on

What is the difference between a conversion failure and a domain validation failure? Why should both occur before a task enters the repository?

Was this article helpful?

Your response is saved on this device.