How to Report Invalid Input, Close Files, and Decide When to Stop
A librarian opens an inventory file. The first line says there are three copies for B-101. The second says B-102;two. Java can turn "3" into a number, but what should the import do when it reaches "two"? There is another valid count farther down the file. Whether it should appear in the report depends on what the librarian needs the report for.
We’ll build on the same library from Java Collections for Beginners: Two Books, One Title, Three Scans. This time, the input comes from a file and a list holds the accepted rows. The examples assume you can follow a loop, call a method, and add an item to a list. For a refresher, see Java for Beginners in 2026: From Your First Program to Tested Business Rules.
Two small inventory files
The lab reads UTF-8 text without a byte order mark. Each line has an inventory ID and a quantity separated by one semicolon. An ID is a nonempty sequence of letters A–Z or a–z, digits or hyphens. The quantity must fit in a Java int and be zero or greater. Use plain fields without padding, a header, quotes or escaping. A blank line is an invalid row. Each row is considered independently and the lab keeps accepted entries in input order.
The clean file, examples/clean.txt:
B-101;3
B-102;2
B-104;0
The mixed file, examples/mixed.txt:
B-101;3
B-102;two
B-103;-1
B-104;4
Line 2 asks Java to turn a word into an integer. Line 3 contains an integer Java can read, but the library’s counting rule rejects it. Line 4 gives us a way to see whether the program kept going.
See the program run
You can follow all four runs below. Each card shows the command, the exit code returned to the shell and the actual console output from the downloaded lab. An exit code is a number the shell can use to tell how the program ended.
Clean file
java -cp out InventoryImport tolerant examples/clean.txt
Exit code 0
Three lines appear as accepted, including the zero count on line 3. “Complete” means every row passed.
Selectable console output
Line 1: B-101 x 3
Line 2: B-102 x 2
Line 3: B-104 x 0
Complete: 3 accepted.
Mixed file, tolerant mode
java -cp out InventoryImport tolerant examples/mixed.txt
Exit code 1
Line 2 needs a number and line 3 needs a nonnegative count. Line 4 still appears among the accepted entries. “Partial” gives both totals.
Selectable console output
Line 2: Invalid quantity 'two'. Use an int such as 2.
Line 3: Negative quantity. Use 0 or more.
Line 1: B-101 x 3
Line 4: B-104 x 4
Partial: 2 accepted, 2 rejected.
Same file, strict mode
java -cp out InventoryImport strict examples/mixed.txt
Exit code 2
The same file stops at line 2. The program emits a correction for that line and ends before printing any accepted entries or a total.
Selectable console output
Import stopped. Line 2: Invalid quantity 'two'. Use an int such as 2.
Missing file
java -cp out InventoryImport tolerant examples/missing.txt
Exit code 3
The command fails before it can read a row. Check the relative path and retry with an existing file.
Selectable console output
Import failed. File not found.
Check the path: examples/missing.txt
How a bad quantity becomes a row error
The parser turns one line into an entry. It checks the two fields, then calls Integer.parseInt to convert the quantity. Here is the part that handles the conversion.
int quantity;
try {
quantity = Integer.parseInt(fields[1]);
} catch (NumberFormatException cause) {
throw new InvalidInventoryRowException(lineNumber,
"Invalid quantity '" + fields[1] + "'. Use an int such as 2.", cause);
}
The try block contains the conversion we want to attempt. When parseInt receives "two", it throws a NumberFormatException. An exception is an object that carries details about what went wrong and changes where the program continues. Here, the assignment to quantity never finishes. Java jumps to the matching catch block. That block knows the file line number and the expected input, so it uses throw to send a new exception back to its caller with those details. Java SE 25 · Integer.parseInt, JLS §11 · Exceptions
The custom exception supplies the line number in its message and saves the original exception as the cause. The person editing the file gets a correction they can make. A developer can still trace the failure back to the conversion.
InvalidInventoryRowException(int lineNumber, String message, Throwable cause) {
super("Line " + lineNumber + ": " + message, cause);
}
For "-1", the assignment finishes. The next check rejects the negative quantity and throws the same custom exception. There is no conversion failure to attach.
if (quantity < 0) {
throw new InvalidInventoryRowException(lineNumber,
"Negative quantity. Use 0 or more.");
}
return new Entry(lineNumber, fields[0], quantity);
Both bad lines skip return new Entry(...). The caller gets a row error in either case, with a different explanation for each.
Who decides whether to keep going?
The import loop calls the parser. If the parser throws, the call to entries.add(...) never runs for that row. The loop has enough context to decide what to do next because it knows which mode the librarian picked.
while ((line = reader.readLine()) != null) {
lineNumber++;
try {
entries.add(parseRow(line, lineNumber));
} catch (InvalidInventoryRowException problem) {
if (mode == Mode.STRICT) {
throw problem;
}
problems.add(problem.getMessage());
}
}
In tolerant mode, the catch saves the message and the next iteration reads another line. After the file has been read and closed, the command prints the warnings, accepted entries and partial summary. Line 4 in the gallery shows that the loop resumed after line 3.
In strict mode, throw problem sends the same exception out of the loop. The remaining rows and the return of the report are skipped. The import method closes the reader as it exits. At the command-line boundary, importFile(...) throws, so printReport(...) is skipped and the row-error catch takes over.
Report report = importFile(file, mode, readerSource);
return printReport(report, out, err);
} catch (InvalidInventoryRowException problem) {
err.println("Import stopped. " + problem.getMessage());
if (debug) {
problem.printStackTrace(err);
}
return 2;
A partial report can help staff review one shelf at a time. They can work with valid counts and use the rejected line numbers to make corrections. A final inventory that replaces the library’s official counts needs every intended row. In that case, require a complete input file and stop on the first row error. A real replacement import would also need checks for completeness and duplicate IDs. This lab checks individual rows.
The lab builds its report in memory. If an import has already written counts to a database or replaced a file, throwing an exception leaves completed writes in place. For a database import that must succeed as a whole, validate before writing and use a transaction so the writes can be committed together or rolled back.
Why file errors end both modes
Look at the position of reader.readLine() in the loop. It is outside the try that handles parse errors. A missing file prevents the reader from opening. A read or decoding failure interrupts the stream of rows, so the import cannot establish what the rest of the file contains. Even tolerant mode requires the file to be read to the end and closed successfully.
IOException is a checked exception. If the loop calls readLine() without catching IOException, Java requires the method to declare throws IOException. Removing the declaration while leaving the call unhandled makes compilation fail. The same contract applies at each call site until a method catches the exception. The custom row exception is checked too because it extends Exception directly. At the CLI, one catch handles the row error, a more specific NoSuchFileException catch tells the user to check the path, and an IOException catch handles other file failures. JLS §11.2 · Compile-time checking
NumberFormatException is unchecked because it belongs to the RuntimeException family. The compiler lets a caller leave it uncaught. Here we catch it on purpose because a typo in user input is something a librarian can correct. The checked/unchecked label governs the compiler contract. The operation and its purpose determine whether the application can recover. Java’s Error branch also contains unchecked types. It covers problems such as running out of memory and is outside the row-recovery logic. JLS §11.1.1 · Exception classes
Close the reader even when the import stops
A finally block runs when control leaves a try and any matching catch, including on a normal return or when an exception propagates. An application might use it to clear a “count in progress” indicator on either outcome. That is an application cleanup action. Closing the reader releases a file resource.
Keep finally focused on cleanup. In this small tested mistake, the method returns 0 even though the body throws. A new exception thrown from finally can also replace the one already on its way out.
static int maskedFailure() {
try {
throw new IllegalStateException("import failed");
} finally {
return 0;
}
}
For a reader, Java can manage the close for us. The lab’s command-line entry passes Files::newBufferedReader, shorthand for calling Files.newBufferedReader(file). That overload reads UTF-8. The tests pass a substitute reader so they can simulate an I/O failure at a precise point.
static Report importFile(Path file, Mode mode, OpenReader readerSource)
throws IOException, InvalidInventoryRowException {
try (BufferedReader reader = readerSource.open(file)) {
return readRows(reader, mode);
}
}
The parentheses declare the resource in a try-with-resources statement. After opening succeeds, Java calls close() when the block ends, including when strict mode rethrows a row error. The report reaches the caller only after close succeeds. If both the body and close throw, Java keeps the body exception and attaches the close failure as a suppressed exception, which remains available for diagnosis. JLS §14.20 · The try statement, Dev.java · Catching and Handling Exceptions, Java SE 25 · Files.newBufferedReader
Read a stack trace when you need one
The normal console message tells the librarian where to edit the file. For developer diagnostics, add --debug to the strict command. Here are selected lines from that run. The full trace also includes the intervening Java library and application frames.
InvalidInventoryRowException: Line 2: Invalid quantity 'two'. Use an int such as 2.
at InventoryImport.parseRow(InventoryImport.java:122)
at InventoryImport.readRows(InventoryImport.java:84)
[…]
Caused by: java.lang.NumberFormatException: For input string: "two"
[…]
at InventoryImport.parseRow(InventoryImport.java:120)
The first line gives the exception type and message. The first at line for our code points to the throw in InventoryImport.parseRow. The following frames show how the call arrived there. Caused by shows the original NumberFormatException, and the frame from that part of the trace points to the conversion itself. Those are two different lines in the same method.
One easy mistake is to catch the right type and do nothing with it. This version returns zero for B-102;two without saying the row was rejected. If you sum counts like this into an import report, a row can disappear while the report looks complete.
static int silentCount(String line) {
int accepted = 0;
try {
InventoryImport.parseRow(line, 2);
accepted++;
} catch (InvalidInventoryRowException ignored) {
}
return accepted;
}
Try predicting the effect of changing only two to 2 in the mixed file. Tolerant mode should now accept one more row. Strict mode should report the next problem, the negative quantity on line 3.
Run the lab yourself
Download the library inventory lab ZIP
The ZIP contains the Java source, both example files, tests and a README with commands for Windows, Linux and macOS. The gallery uses Eclipse Temurin 25.0.5.1+2 on Windows x64. Tests simulate a read failure after one valid entry and a separate failure while closing the file. Both runs produce an I/O diagnostic and no accepted entries or completion summary. Eclipse Temurin 25.0.5.1+2 release