GNGiseldo Neo and Alana NeoBooks
Introduction to Programming in Java10 / 25

Error Handling and Files

Recovering from invalid input and persisting conversation history

9.1 Learning objectives

By the end of this chapter, you should be able to:

  • distinguish compile-time errors, exceptions, and logic errors;
  • catch only exceptions that can be meaningfully handled at that point;
  • repeat input reading until a valid value is received;
  • throw IllegalArgumentException when a contract is violated;
  • save text to a file while handling IOException.

9.2 Expected exceptions

Recovering from invalid input.

Figure 9.1. Recovering from invalid input.

In interactive programs, invalid inputs are expected. Integer.parseInt throws NumberFormatException when text does not represent an integer:

try {
    int age = Integer.parseInt(input);
    System.out.println("Age: " + age);
} catch (NumberFormatException error) {
    System.out.println("Enter an integer.");
}

Do not catch Exception unnecessarily. A specific type documents the expected failure mode and avoids masking unrelated bugs.

9.3 Retrying until a valid value is entered

import java.util.Scanner;

static int readInteger(Scanner scanner, String prompt) {
    while (true) {
        System.out.print(prompt);
        String input = scanner.nextLine();

        try {
            return Integer.parseInt(input);
        } catch (NumberFormatException error) {
            System.out.println("Invalid value. Please try again.");
        }
    }
}

Reading and recovery stay in one place. The rest of the program receives a guaranteed valid integer.

9.4 Throwing an exception

Comic: catching every exception.

Figure 9.2. Comic: catching every exception.

Throw an exception when the caller violates a method’s contract:

static void validateAge(int age) {
    if (age < 0 || age > 130) {
        throw new IllegalArgumentException("Age out of range.");
    }
}

Whether to catch or propagate depends on responsibility. A console interface can catch an exception and display guidance; a domain class usually throws the exception and leaves handling to the outer layer.

9.5 Persistence with try-with-resources

The Files API simplifies writing lines and manages closing the file automatically:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

static void saveHistory(Path file, List<String> lines)
        throws IOException {
    Files.write(file, lines);
}

Handle the failure at the outer boundary of the program:

try {
    saveHistory(Path.of("history.txt"), history);
    System.out.println("History saved.");
} catch (IOException error) {
    System.out.println("Could not save history.");
    System.err.println("Technical detail: " + error.getMessage());
}

The user-facing message stays brief; technical details go to the error stream.

9.6 Complete example

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

public class Chapter09ErrorsAndFiles {
    public static void saveHistory(Path file, List<String> lines)
            throws IOException {
        Files.write(file, lines);
    }

    public static void main(String[] args) {
        List<String> history = List.of("USER: hi", "BOT: Hello!");

        try {
            saveHistory(Path.of("history.txt"), history);
            System.out.println("History saved.");
        } catch (IOException error) {
            System.out.println("Could not save history.");
            System.err.println(error.getMessage());
        }
    }
}

9.7 Project evolution: version 9

The chatbot recovers from invalid numeric inputs and offers to save the conversation history on exit. A write failure does not lose the conversation or print a raw stack trace to the user.

The complete example is in examples/src/Chapter09ErrorsAndFiles.java.

9.8 Verifiable practice

  1. Read an age repeatedly until you get a number between 0 and 130.
  2. Save three messages to history.txt.
  3. Test an invalid file path and confirm the friendly error message appears.
  4. Explain why NumberFormatException and IOException are handled in different places.

Do not use exceptions for routine validation

Simple conditions such as blank text should be checked directly. Exceptions are appropriate when an operation cannot fulfill its contract.