Skip to lesson

Designing error handling: practice

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Good error handling is a set of small decisions made the same way every time: what to catch, what to throw, what to log and what to tell the user. These exercises put all of them together on small, realistic programs.

Refactor a program that swallows errors

Refactoring weak error handling starts with a search for every empty catch, every catch (Exception e) and every printStackTrace(). For each one, decide whether to handle it, translate it or remove the catch and let the error go up.

Example 1 · Refactored: an importer that no longer hides bad rows

AttendanceRefactorDemo.javaJava
import java.util.ArrayList;import java.util.List;
public class AttendanceRefactorDemo {    // Before: errors are swallowed, so the count is wrong    static int importOld(List<String> rows) {        int imported = 0;        for (String row : rows) {            try {                Integer.parseInt(row.split(",")[1].trim());            } catch (Exception e) {                // ignore            }            imported++;        }        return imported;    }
    // After: catch only what we can handle, count it and report it    static int[] importNew(List<String> rows, List<String> problems) {        int imported = 0;        for (int i = 0; i < rows.size(); i++) {            String[] parts = rows.get(i).split(",");            if (parts.length != 2) {                problems.add("Row " + (i + 1) + ": expected roll,days but got '" + rows.get(i) + "'");                continue;            }            try {                Integer.parseInt(parts[1].trim());                imported++;            } catch (NumberFormatException e) {                problems.add("Row " + (i + 1) + ": days '" + parts[1].trim() + "' is not a number");            }        }        return new int[]{imported, problems.size()};    }
    public static void main(String[] args) {        List<String> rows = List.of("101,22", "102,twenty", "103", "104,25");
        System.out.println("Old: imported " + importOld(rows) + " rows");
        List<String> problems = new ArrayList<>();        int[] result = importNew(rows, problems);        System.out.println("New: imported " + result[0] + ", rejected " + result[1]);        problems.forEach(p -> System.out.println("  " + p));    }}
Output
Old: imported 4 rows
New: imported 2, rejected 2
  Row 2: days 'twenty' is not a number
  Row 3: expected roll,days but got '103'

What this code does

  • The old version catches Exception (which also hides the ArrayIndexOutOfBoundsException from row 3) and counts every row as imported, so its report is simply false.
  • The new version checks the shape of each row first, catches only NumberFormatException, and collects one clear line per problem, so the count and the report are both honest.

Handle means skip the item, use a default, tell the user, and count it. Translate means wrap the exception with the cause.

The goal is that every failure becomes visible somewhere: in a count, a report line, a log entry or a user message. A batch job that says "imported 4 rows" when two were bad is worse than one that stops.

Add logging and user messages

Next, give each failure the right audience. The top-level handler logs unexpected errors once, at SEVERE, with the exception attached; app exceptions with user-ready messages are shown as they are.

Example 2 · One log entry for developers, one sentence for users

ReceiptHandlerDemo.javaJava
import java.io.IOException;import java.util.logging.Level;import java.util.logging.Logger;
class FeeAppException extends RuntimeException {    FeeAppException(String message) { super(message); }    FeeAppException(String message, Throwable cause) { super(message, cause); }}
public class ReceiptHandlerDemo {    static {   // only for this page: short log lines on System.out (no date, no stack trace)        System.setErr(System.out);        System.setProperty("java.util.logging.SimpleFormatter.format", "%4$s: %5$s%n");    }
    private static final Logger LOG = Logger.getLogger(ReceiptHandlerDemo.class.getName());    static int nextRef = 501;
    static void saveReceipt(String roll) throws IOException {        if (roll.equals("102")) {            throw new IOException("disk is full");        }    }
    static void printReceipt(String roll) {        if (roll.equals("103")) {            throw new FeeAppException("No payment found for roll 103. Pay first, then print the receipt.");        }        try {            saveReceipt(roll);        } catch (IOException e) {            throw new FeeAppException("Could not save the receipt for roll " + roll, e);        }        System.out.println("Receipt saved for roll " + roll);    }
    static void handle(String roll) {        try {            printReceipt(roll);        } catch (FeeAppException e) {            if (e.getCause() == null) {                System.out.println(e.getMessage());                      // written for users            } else {                String ref = "RC-" + nextRef++;                LOG.log(Level.SEVERE, ref + " " + e.getMessage(), e);   // the one log entry                System.out.println("Sorry, the receipt could not be saved. Reference: " + ref);            }        }    }
    public static void main(String[] args) {        handle("101");        handle("102");        handle("103");    }}
Output
Receipt saved for roll 101
SEVERE: RC-501 Could not save the receipt for roll 102
Sorry, the receipt could not be saved. Reference: RC-501
No payment found for roll 103. Pay first, then print the receipt.

What this code does

  • printReceipt only translates the IOException, keeping the cause, and does not log. handle is the single place that logs, so the disk error appears in the log exactly once, with a reference id.
  • An app exception without a cause carries a message written for users (roll 103), so it is shown as it is. One with a technical cause gets a calm sentence and the reference to quote.

Link the two with a reference id, keep paths and personal data out of the user's text, and remove any log calls from lower layers that only rethrow. After this step, a user sees one calm sentence and a developer finds one complete log entry.

Design exceptions for a booking app

Designing from scratch follows the module in order: decide checked or unchecked, create one base exception, and add a child only when a caller handles it differently.

Example 3 · Exceptions for a bus booking app

BusBookingDemo.javaJava
import java.util.HashSet;import java.util.Objects;import java.util.Set;
class BookingException extends RuntimeException {               // base, unchecked    BookingException(String message) { super(message); }}
class SeatTakenException extends BookingException {    private final int seat;
    SeatTakenException(int seat) {        super("Seat " + seat + " is already booked.");        this.seat = seat;    }
    int seat() { return seat; }}
record BookingRequest(String passenger, int seat) {    static final int SEATS = 40;
    BookingRequest {        Objects.requireNonNull(passenger, "passenger must not be null");        if (seat < 1 || seat > SEATS) {            throw new IllegalArgumentException("seat must be 1 to " + SEATS + ", got " + seat);        }    }}
class Bus {    private final Set<Integer> booked = new HashSet<>();
    void book(BookingRequest r) {        if (booked.size() == BookingRequest.SEATS) {            throw new BookingException("This bus is full. Try the next departure.");        }        if (!booked.add(r.seat())) {            throw new SeatTakenException(r.seat());        }        System.out.println("Seat " + r.seat() + " booked for " + r.passenger());    }
    int nextFreeSeat(int from) {        for (int s = from; s <= BookingRequest.SEATS; s++) {            if (!booked.contains(s)) return s;        }        return -1;    }}
public class BusBookingDemo {    static void handle(Bus bus, String passenger, int seat) {        try {            bus.book(new BookingRequest(passenger, seat));        } catch (SeatTakenException e) {            System.out.println(e.getMessage() + " Seat " + bus.nextFreeSeat(e.seat()) + " is free.");        } catch (BookingException e) {            System.out.println(e.getMessage());        } catch (IllegalArgumentException e) {            System.out.println("Bug: " + e.getMessage());        }    }
    public static void main(String[] args) {        Bus bus = new Bus();        handle(bus, "Asha", 12);        handle(bus, "Neel", 13);        handle(bus, "Ravi", 12);        handle(bus, "Isha", 45);    }}
Output
Seat 12 booked for Asha
Seat 13 booked for Neel
Seat 12 is already booked. Seat 14 is free.
Bug: seat must be 1 to 40, got 45

What this code does

  • SeatTakenException exists as its own class because one caller treats it differently: it reads the seat field and suggests the next free seat. A full bus needs no special handling, so it is a plain BookingException.
  • Seat 45 never reaches the Bus: the record's compact constructor rejects it. Since the seat picker should never offer 45, handle reports it as a bug.

Most app exceptions are unchecked; the top-level handler deals with them. Give exceptions fields such as the seat number.

Validate requests in a record's compact constructor, so a bad seat number never reaches the booking logic. Then write the top-level handler that turns each exception into a message.

Retry a file read

A file read that sometimes fails because another program holds the file is a good place for a bounded retry: a helper with a limit and a growing wait that retries only temporary errors.

Example 4 · A file read with retry, translation and no retry for missing files

RetryReadDemo.javaJava
import java.io.IOException;import java.nio.file.Files;import java.nio.file.NoSuchFileException;import java.nio.file.Path;
class StorageException extends RuntimeException {    StorageException(String message, Throwable cause) { super(message, cause); }}
public class RetryReadDemo {    static int busyReads = 2;     // stands in for another program holding the file twice
    static String readOnce(Path file) throws IOException {        if (busyReads > 0) {            busyReads--;            throw new IOException("file is being used by another process");        }        return Files.readString(file).trim();    }
    static String readWithRetry(Path file, int maxAttempts) {        long wait = 50;        for (int attempt = 1; ; attempt++) {            try {                return readOnce(file);            } catch (NoSuchFileException e) {                throw new StorageException("Timetable file is missing", e);     // permanent            } catch (IOException e) {                System.out.println("Attempt " + attempt + " failed: " + e.getMessage());                if (attempt == maxAttempts) {                    throw new StorageException("Gave up reading the timetable", e);                }                try {                    Thread.sleep(wait);                } catch (InterruptedException ie) {                    Thread.currentThread().interrupt();                    throw new StorageException("Interrupted while reading the timetable", ie);                }                wait *= 2;            }        }    }
    public static void main(String[] args) throws IOException {        Path folder = Files.createTempDirectory("tt");        Path file = folder.resolve("timetable.txt");        Files.writeString(file, "Mon: DBMS 9:00, OS 11:00");
        System.out.println(readWithRetry(file, 3));        try {            readWithRetry(folder.resolve("missing.txt"), 3);        } catch (StorageException e) {            System.out.println(e.getMessage() + " (" + e.getCause().getClass().getSimpleName() + ")");        }
        Files.delete(file);        Files.delete(folder);    }}
Output
Attempt 1 failed: file is being used by another process
Attempt 2 failed: file is being used by another process
Mon: DBMS 9:00, OS 11:00
Timetable file is missing (NoSuchFileException)

What this code does

  • The first two reads fail with a temporary error, so the helper waits (50 ms, then 100 ms) and the third read returns the real file content.
  • NoSuchFileException has its own catch block before IOException, so the missing file is translated at once with no pointless retries. Every way out of the helper is a StorageException with the cause attached.

Permanent errors such as NoSuchFileException are rethrown at once. When the retries run out, translate the last exception into the app's own StorageException with the cause, so the top-level handler can show a message and log the details.

Finish up

Mark complete & continue

Next: CSV expense tracker