Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java exception exercises: all-or-nothing parsing of a small batch

Last updated: 29 Sept 20264 min read
tutorial
IntermediateBy AITrove Editorial

Batch parsing can return a complete validated result or fail before exposing that result; a partially filled caller-owned list breaks that boundary.

Java 8+. This is a complete program using JDK classes.

Specify the rejected cases

Parse an array of quantity strings into positive int values. Reject a null member, malformed number, zero or negative value. The accepted output must preserve the input order, and the input strings must remain unchanged.

The solution builds private output storage. It can abandon that storage on failure without editing a previously published collection. This is an application-level boundary, not a database transaction and not a promise to roll back arbitrary callbacks performed during parsing.

Use exception tests that fail when the operation unexpectedly succeeds. A catch block that merely prints an error can pass even when no error happened. The supplied helper throws its own AssertionError after an accepted invalid input, so the test cannot silently skip the rejection requirement.

Working program

Java
import java.util.*;
public class QuantityBatchExercises {
    static List<Integer> parse(String[] lines){
        List<Integer> accepted=new ArrayList<>();
        for(String line:lines){
            if(line==null)throw new IllegalArgumentException("Missing quantity");
            int quantity=Integer.parseInt(line);
            if(quantity<=0)throw new IllegalArgumentException("Positive quantity required");
            accepted.add(quantity);
        }
        return Collections.unmodifiableList(accepted);
    }
    static void rejected(String[] lines){
        try{parse(lines);throw new AssertionError("Invalid batch accepted");}
        catch(IllegalArgumentException expected){ }
    }
    public static void main(String[] args){
        if(!parse(new String[]{"3","7"}).equals(Arrays.asList(3,7)))throw new AssertionError("Wrong order");
        rejected(new String[]{"3","bad"});rejected(new String[]{"0"});rejected(new String[]{null});
        System.out.println("4 parsing checks passed");
    }
}

Output

Output
4 parsing checks passed

Costs and boundaries

Parsing work is proportional to the total input characters, with O(n) integer-reference storage for n accepted values. Large input also needs a byte, line and record-count budget before reaching this method. The empty array yields an empty result under this contract.

Common Mistakes

  • Do not fill caller-owned output before the batch is validated.
  • A rejection test must fail when invalid input is accepted.
  • Catching NumberFormatException does not make zero a valid business quantity.

Read next

Catch boundaries, Validated file imports.

java
exception-exercises
Storage details