SyntaxPilot
Courses/Low-Level Design/Lesson 54
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Low-Level Design · Lesson 54 of 90

Error handling, validation and class API design

exceptions vs error codesfail fastguard clausesinput validationdomain exceptionsexception hierarchy designResult typenull-safety conventionsimmutability by defaultminimal public APIpackage structurepackage-by-feature vs package-by-layerdocumentation with Javadoc

These are the notes for Low-Level Design (LLD) episode 54. In episode 53 we made classes testable; now we make them hard to misuse. At Ravi's canteen wallet we invent the whole toolkit from failures you can see: an error code nobody checks (a free thali), exceptions that can't be ignored, failing fast with guard clauses and input validation, domain exceptions in a small exception hierarchy, a Result type for failures that are normal, null-safety conventions with Optional, immutability by default, a minimal public API, package structure (package-by-feature vs package-by-layer) and documentation with Javadoc.

How the code was run: every compiler program with javac Main.java && java -cp . Main on OpenJDK 21. The package and Javadoc outputs come from OpenJDK 21.0.12 javac and javadoc run on the files shown. All outputs are real.

1. The real-life idea: errors at Ravi's canteen counter

Ravi's canteen has a prepaid wallet: students load money and pay for food from it.

At the canteen In code
A note slipped under the door: easy to never read Error code: a special return value (like -1) the caller can ignore
The fire alarm: everyone must react Exception: thrown, stops the normal flow, must be handled somewhere
The guard checks your ID at the gate, not at the dining table Fail fast: reject bad input at the door
The cash box is locked; customers use the counter Minimal public API: private inside, small public face

2. Exceptions vs error codes

An error code is a return value that means "success" or "a kind of failure", for example 0 = paid, -1 = not enough money.

The problem: an error code nobody checks

class Wallet {
    private long balance = 100;
    int pay(long rupees) {                       // 0 = paid, -1 = not enough money
        if (rupees > balance) return -1;
        balance -= rupees;
        return 0;
    }
    long balance() { return balance; }
}
public class Main {
    public static void main(String[] args) {
        Wallet asha = new Wallet();
        asha.pay(250);                           // the -1 is silently ignored
        System.out.println("Thali served to Asha");
        System.out.println("Wallet balance: Rs " + asha.balance());
    }
}

Output (real):

Thali served to Asha
Wallet balance: Rs 100

The payment failed, nobody checked the -1, and Asha got a free thali with her balance untouched. Nothing crashed: the bug is silent.

Why error codes fail:

  1. Easy to ignore. Java doesn't make you look at a return value.
  2. Mixed with real results. If a method returns a balance, is -1 an error or a real balance of minus one?
  3. Manual passing. Every caller in the chain must check the code and return it upward; forget once and the error vanishes.

An exception is an object that is thrown with the throw keyword. It stops the normal flow at once, carries a message, and travels up the call chain until a catch handles it. If nothing catches it, the program stops and prints a stack trace: the list of method calls that led to the error, newest first.

The fix: an exception nobody can ignore

class Wallet {
    private long balance = 100;
    void pay(long rupees) {
        if (rupees > balance)
            throw new IllegalStateException("balance Rs " + balance + ", need Rs " + rupees);
        balance -= rupees;
    }
    long balance() { return balance; }
}
public class Main {
    public static void main(String[] args) {
        Wallet asha = new Wallet();
        asha.pay(250);                           // can't be ignored any more
        System.out.println("Thali served to Asha");
        System.out.println("Wallet balance: Rs " + asha.balance());
    }
}

Output (real):

Exception in thread "main" java.lang.IllegalStateException: balance Rs 100, need Rs 250
    at Wallet.pay(Main.java:5)
    at Main.main(Main.java:13)

IllegalStateException is Java's built-in exception for "this object is not in a state to do that". The "Thali served" line never runs.

Where error codes still fit: languages without exceptions (C), a program's exit code to the operating system (0 = success), and HTTP status codes like 404. Inside a Java design, use exceptions for failures.

3. Fail fast: guard clauses and input validation

Failing late means bad data is accepted, travels through the program, and the crash happens somewhere far from the mistake.

import java.util.*;
class MenuItem {
    final String name; final long price;
    MenuItem(String name, long price) { this.name = name; this.price = price; }   // accepts anything
}
class Bill {
    private final List<MenuItem> items = new ArrayList<>();
    void add(MenuItem item) { items.add(item); }
    String print() {
        StringBuilder out = new StringBuilder(); long total = 0;
        for (MenuItem m : items) {
            out.append(m.name.toUpperCase()).append("  Rs ").append(m.price).append("\n");
            total += m.price;
        }
        return out.append("TOTAL Rs ").append(total).toString();
    }
}
public class Main {
    public static void main(String[] args) {
        Bill bill = new Bill();
        bill.add(new MenuItem("Masala dosa", 80));
        bill.add(new MenuItem("Chai", -15));                // a typo: minus 15
        bill.add(new MenuItem(null, 40));                   // the name never arrived
        // ... 500 lines later, at the cash counter ...
        System.out.println(bill.print());
    }
}

Output (real):

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.toUpperCase()" because "<local5>.name" is null
    at Bill.print(Main.java:12)
    at Main.main(Main.java:25)

Java's "helpful NullPointerException" message says exactly where it crashed (Bill.print, line 12), but that is the wrong place: the null came from the third add, and the -15 chai would have been billed silently. (<local5> is how the JVM names a local variable when the class was compiled without debug information; with javac -g it would say m.)

Failing fast means checking inputs first and throwing immediately, at the exact place the mistake was made.

  • A guard clause is a check at the very top of a method or constructor that throws (or returns) when something is wrong. Guards first, then the real work, no nesting.
  • Objects.requireNonNull(x, "x") throws a NullPointerException whose message is the name you gave, if x is null.
  • IllegalArgumentException is the built-in exception for "the caller passed a bad argument".
  • Input validation means checking data that comes from outside your code (a form, a file, a network request) where it enters, so the inside of the design can trust it.
import java.util.*;
class MenuItem {
    final String name; final long price;
    MenuItem(String name, long price) {
        Objects.requireNonNull(name, "name");                              // guard clauses:
        if (name.isBlank()) throw new IllegalArgumentException("name is blank");    // check first,
        if (price <= 0) throw new IllegalArgumentException("price must be positive: " + price);
        this.name = name; this.price = price;                              // then do the work
    }
}
public class Main {
    public static void main(String[] args) {
        System.out.println("Dosa ok: " + new MenuItem("Masala dosa", 80).price);
        try { new MenuItem(null, 40); }
        catch (NullPointerException e) { System.out.println("rejected: " + e.getMessage()); }
        new MenuItem("Chai", -15);                          // fails right here, at the source
        System.out.println("never printed");
    }
}

Output (real):

Dosa ok: 80
rejected: name
Exception in thread "main" java.lang.IllegalArgumentException: price must be positive: -15
    at MenuItem.<init>(Main.java:7)
    at Main.main(Main.java:16)

The exception now points at Main.main line 16, the line that made the mistake, and a MenuItem can never exist in a broken state.

Guard clauses vs nested ifs

Nested ifs ("arrow code", because it drifts right like an arrow head):

String serve(Order o) {
  if (o != null) {
    if (!o.isEmpty()) {
      if (wallet.canPay(o.total())) {
        wallet.pay(o.total());
        return "served";
      } else {
        return "top up";
      }
    } else {
      return "empty order";
    }
  } else {
    throw new NullPointerException();
  }
}

The same logic with guard clauses: every bad case on top, the happy path (the normal case) reads straight down.

String serve(Order o) {
  Objects.requireNonNull(o, "order");
  if (o.isEmpty()) return "empty order";
  if (!wallet.canPay(o.total())) return "top up";

  wallet.pay(o.total());
  return "served";
}

Validating outside input

Text from a user must be checked before it is trusted. Parsing it without a check fails like this (real):

Integer.parseInt("two");
Exception in thread "main" java.lang.NumberFormatException: For input string: "two"
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
    at java.base/java.lang.Integer.parseInt(Integer.java:662)

Validate at the boundary (where the data enters): catch NumberFormatException there and turn it into a clear message for the user, or check the text with a pattern first.

4. Domain exceptions and exception hierarchy design

The problem: catching by message

class Wallet {
    private long balance = 100; private boolean blocked = false;
    void pay(long rupees) {
        if (blocked) throw new IllegalStateException("wallet is blocked");
        if (rupees > balance)          // a teammate reworded this message last week:
            throw new IllegalStateException("not enough money: " + balance + " < " + rupees);
        balance -= rupees;
    }
}
public class Main {
    public static void main(String[] args) {
        try {
            new Wallet().pay(250);
        } catch (IllegalStateException e) {
            if (e.getMessage().contains("balance")) System.out.println("Please top up");
            else System.out.println("Sorry, something went wrong");   // the wrong branch
        }
    }
}

Output (real):

Sorry, something went wrong

The caller decided what to do by reading the message text. A teammate reworded the message, and the caller took the wrong branch. Messages are for humans; code must not depend on their exact words. And the caller can't get numbers (how much short?) out of a string.

The fix: domain exceptions

  • The domain is the real-world area your code models (here, a canteen wallet).
  • A domain exception is an exception class named in the language of that domain, like InsufficientBalanceException, instead of a general one.
  • The type says what happened, so callers catch by type. Fields carry the data (shortBy).
  • An exception hierarchy is a family tree of exception classes. Good design: Java's RuntimeException at the top (so callers aren't forced to catch), one base class per module (WalletException), and specific children under it.
  • A caller can catch a specific child to react to it, or the base to handle every wallet problem in one place.
  • Checked or unchecked? (episode 5) Checked exceptions must be declared with throws and caught; unchecked ones (subclasses of RuntimeException) need not be. Most modern designs use unchecked exceptions for domain errors and reserve checked ones for recoverable I/O-style failures the caller must think about.
abstract class WalletException extends RuntimeException {          // the family's base
    WalletException(String message) { super(message); }
}
class InsufficientBalanceException extends WalletException {
    final long shortBy;                                              // data, not just text
    InsufficientBalanceException(long have, long need) {
        super("balance Rs " + have + ", need Rs " + need); shortBy = need - have; }
}
class WalletBlockedException extends WalletException {
    WalletBlockedException(String owner) { super(owner + "'s wallet is blocked"); }
}
record Wallet(String owner, long balance, boolean blocked) {
    void pay(long rupees) {
        if (blocked) throw new WalletBlockedException(owner);
        if (rupees > balance) throw new InsufficientBalanceException(balance, rupees);
    }
}
public class Main {
    static void order(Wallet w, long rupees) {
        try { w.pay(rupees); System.out.println("Served, Rs " + rupees); }
        catch (InsufficientBalanceException e) { System.out.println("Top up Rs " + e.shortBy + " more"); }
        catch (WalletBlockedException e) { System.out.println("Ask the counter: " + e.getMessage()); }
    }
    public static void main(String[] args) {
        order(new Wallet("Asha", 300, false), 250);
        order(new Wallet("Ravi", 100, false), 250);
        order(new Wallet("Neha", 900, true), 250);
    }
}

Output (real):

Served, Rs 250
Top up Rs 150 more
Ask the counter: Neha's wallet is blocked

(To keep the program on one screen, Wallet is a record here, so pay only checks and doesn't deduct.)

Exception hierarchy design rules:

Rule Why
One base class per module (WalletException) Callers can catch "anything from wallets" in one place
Specific children named after the problem The type says what happened
Put data in fields, not only in the message Callers can act on it (shortBy)
Keep it shallow (2-3 levels) Deep trees are hard to remember and to catch correctly
Don't catch Exception and swallow it The error disappears without a trace
Wrap low-level exceptions at module boundaries throw new WalletException("...", sqlException) keeps the cause but hides the detail

5. A Result type for expected failures

Some failures are exceptional (a bug, a broken disk, a blocked wallet); others are expected, everyday outcomes (a student types a wrong coupon code). Using exceptions for normal choices makes the flow hard to follow.

A Result type is a return value that is either Ok (holding the value) or Err (holding the reason). The caller must look inside to get the value, so it can't forget the failure. In Java we build it with a sealed interface (episode 8: only the listed classes may implement it) and records. Because the compiler knows there are exactly two cases, a switch over a Result must handle both.

First attempt, with only the Ok case:

import java.util.Map;
sealed interface Result<T> permits Ok, Err {}
record Ok<T>(T value) implements Result<T> {}
record Err<T>(String reason) implements Result<T> {}
public class Main {
    static final Map<String, Long> COUPONS = Map.of("CHAI10", 10L, "THALI50", 50L);
    static Result<Long> applyCoupon(String code, long total) {      // a bad code is NORMAL
        Long off = COUPONS.get(code);
        if (off == null) return new Err<>("unknown coupon " + code);
        if (total < 100) return new Err<>(code + " needs a bill of Rs 100 or more");
        return new Ok<>(total - off);
    }
    static void show(String code, long total) {
        switch (applyCoupon(code, total)) {
            case Ok<Long>(Long newTotal) -> System.out.println(code + ": pay Rs " + newTotal);
        }
    }
    public static void main(String[] args) {
        show("THALI50", 220); show("FREEFOOD", 220); show("CHAI10", 60);
    }
}

Compiler output (real):

Main.java:14: error: the switch statement does not cover all possible input values
        switch (applyCoupon(code, total)) {
        ^
1 error

With the Err case added:

            case Err<Long>(String reason) -> System.out.println(code + ": " + reason);

Output (real):

THALI50: pay Rs 170
FREEFOOD: unknown coupon FREEFOOD
CHAI10: CHAI10 needs a bill of Rs 100 or more
Use When
Exception Something is wrong that the caller usually can't fix right here: a bug, broken state, I/O failure
Optional<T> "There may be no value", with no reason needed
Result (Ok / Err) An expected failure where the caller needs the reason

6. Null-safety conventions and Optional

null means "this reference points to no object". It hides in return types.

import java.util.*;
public class Main {
    static final Map<String, Long> MENU = Map.of("chai", 15L, "masala dosa", 80L);
    static Long priceOf(String item) {
        return MENU.get(item);                       // null when the item isn't on the menu
    }
    public static void main(String[] args) {
        long chai = priceOf("chai");
        System.out.println("chai: Rs " + chai);
        long samosa = priceOf("samosa");             // unboxing null
        System.out.println("samosa: Rs " + samosa);
    }
}

Output (real):

chai: Rs 15
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Long.longValue()" because the return value of "Main.priceOf(String)" is null
    at Main.main(Main.java:10)

Turning a Long object into a primitive long is called unboxing; unboxing null throws. Nothing in priceOf's signature warned that it could return nothing.

A convention is a rule a team agrees to follow even though the compiler doesn't force it. Four null-safety conventions:

  1. If a result might be missing, return Optional<T>, never null. The type now says "maybe nothing".
  2. Methods returning a collection return an empty collection, never null, so callers can always loop.
  3. Treat every parameter as non-null by default and enforce it at the door with Objects.requireNonNull.
  4. Optional is for return types. Don't make fields or parameters Optional.
import java.util.*;
public class Main {
    static final Map<String, Long> MENU = Map.of("chai", 15L, "masala dosa", 80L);
    static Optional<Long> priceOf(String item) {     // the type says "maybe missing"
        return Optional.ofNullable(MENU.get(item));
    }
    static List<String> specialsFor(String day) {    // never null: an empty list instead
        return day.equals("Friday") ? List.of("Biryani") : List.of();
    }
    public static void main(String[] args) {
        System.out.println("chai: Rs " + priceOf("chai").orElseThrow());
        priceOf("samosa").ifPresentOrElse(
            p -> System.out.println("samosa: Rs " + p),
            () -> System.out.println("samosa: not on the menu today"));
        System.out.println("Monday specials: " + specialsFor("Monday").size());
    }
}

Output (real):

chai: Rs 15
samosa: not on the menu today
Monday specials: 0
  • Optional.ofNullable(x): empty if x is null, else holds x.
  • orElseThrow(): the value, or NoSuchElementException if empty (use it when you are sure).
  • ifPresentOrElse(action, emptyAction): handles both cases.
  • map(f), orElse(default): transform the value or fall back.

7. Immutability by default

The problem: a getter that leaks the inside

import java.util.*;
class Order {
    private final List<String> items = new ArrayList<>();
    private long total;
    void add(String item, long price) { items.add(item); total += price; }
    List<String> items() { return items; }           // hands out the real list
    long total() { return total; }
}
public class Main {
    public static void main(String[] args) {
        Order order = new Order();
        order.add("Chai", 15);
        order.add("Masala dosa", 80);
        order.items().add("Paneer tikka");           // added from outside, never priced
        System.out.println(order.items() + "  total Rs " + order.total());
    }
}

Output (real):

[Chai, Masala dosa, Paneer tikka]  total Rs 95

Three items, a total for two. The invariant (a rule that must always be true: the total matches the items) was broken from outside. private on the field wasn't enough because the getter handed out the real list.

Mutable means it can change; immutable means it can't change after it is created. Immutability by default means you start with final fields, records and unmodifiable collections (List.copyOf, List.of), and allow change only where change is the point, and then only through the class's own methods. Episode 6's defensive copying becomes the default habit. Bonus: immutable objects are automatically safe to share between threads.

import java.util.*;
record Line(String item, long price) {                  // immutable value object
    Line { if (price <= 0) throw new IllegalArgumentException("price must be positive"); }
}
final class Order {
    private final List<Line> lines = new ArrayList<>();
    void add(String item, long price) { lines.add(new Line(item, price)); }
    List<Line> lines() { return List.copyOf(lines); }   // a read-only copy
    long total() { return lines.stream().mapToLong(Line::price).sum(); }
}
public class Main {
    public static void main(String[] args) {
        Order order = new Order();
        order.add("Chai", 15);
        order.add("Masala dosa", 80);
        System.out.println(order.lines().size() + " lines, total Rs " + order.total());
        order.lines().add(new Line("Paneer tikka", 220));   // try to sneak one in
    }
}

Output (real):

2 lines, total Rs 95
Exception in thread "main" java.lang.UnsupportedOperationException
    at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:142)
    at java.base/java.util.ImmutableCollections$AbstractImmutableCollection.add(ImmutableCollections.java:147)
    at Main.main(Main.java:17)
  • record Line is immutable and its compact constructor rejects bad prices.
  • final class Order can't be subclassed, so no subclass can break its rules.
  • lines() returns List.copyOf(lines): a read-only copy. Writing to it throws UnsupportedOperationException.
  • total() is computed from the lines, so it can never disagree with them.

8. A minimal public API

A class's API (application programming interface) is the set of classes and methods other code is allowed to use.

  • Every public method is a promise: once other code calls it, changing or removing it breaks them.
  • Start private; widen only when a real caller needs it.
  • No setter per field by default; offer actions named in the domain (pay, topUp) that keep the rules (episode 6's tell, don't ask).
  • Package-private (no access modifier at all) for helpers used only inside one package: visible inside the package, invisible outside it.
  • A small API means fewer ways to misuse the class and the freedom to rewrite its inside at any time.
Visibility Who can use it
public Everyone
protected The package, plus subclasses anywhere
(none) package-private Only classes in the same package
private Only the class itself

9. Package structure: by layer or by feature

A package is a folder of related classes with its own name, like canteen.wallet.

by LAYER                          by FEATURE
canteen/                          canteen/
  controller/                       order/
    OrderController.java              OrderController.java
    WalletController.java             OrderService.java
  service/                            OrderRepository.java
    OrderService.java                 Order.java
    WalletService.java              wallet/
  repository/                         Wallet.java      (public)
    OrderRepository.java              WalletService.java (public)
    WalletRepository.java             WalletRepository.java (package-private)
  model/                            menu/
    Order.java  Wallet.java           MenuItem.java
  • Package-by-layer: one package per technical layer (controllers, services, repositories, models). A change to wallets touches four folders, and almost everything must be public because each layer is used from another package.
  • Package-by-feature: one package per piece of the business (order, wallet, menu), each with its own controller, service, repository and model. A wallet change touches one folder, and helpers can be package-private.

The compiler enforces the package boundary (real javac output):

// canteen/wallet/WalletRepository.java
package canteen.wallet;
class WalletRepository {                 // no "public": package-private
    long balanceOf(String owner) { return 100; }
}

// canteen/order/OrderService.java
package canteen.order;
import canteen.wallet.WalletRepository;  // reaching into another feature's insides
public class OrderService { }
$ javac -d out canteen/wallet/*.java canteen/order/*.java
canteen/order/OrderService.java:2: error: WalletRepository is not public in canteen.wallet; cannot be accessed from outside package
import canteen.wallet.WalletRepository;  // reaching into another feature's insides
                     ^
1 error

The order feature must go through the public WalletService instead.

10. Documentation with Javadoc

Javadoc is the JDK tool that turns documentation comments into HTML pages (like the official Java API pages). A documentation comment starts with /** and sits immediately before a class, interface, constructor, method or field.

From Oracle's Documentation Comment Specification: "The first sentence of the main description should be a summary sentence that contains a concise but complete description of the declared entity." Block tags:

Tag Meaning
@param name description Adds the parameter to the "Parameters" section
@return description Adds a "Returns" section: what comes back
@throws ExceptionName description Adds the exception to the "Throws" section: when and why
{@code text} Shows text in code font
package canteen.wallet;

/** A customer's prepaid canteen wallet. Amounts are whole rupees. */
public class Wallet {
    private long balance;

    /**
     * Takes money out of the wallet to pay for an order.
     *
     * @param rupees the amount to pay; must be positive
     * @throws InsufficientBalanceException if the balance is less than {@code rupees}
     */
    public void pay(long rupees) { /* ... */ }

    public long balance() { return balance; }
}

Run on this file plus a documented InsufficientBalanceException, javadoc builds the pages and warns about what is undocumented (real output, ... marks lines left out):

$ javadoc -d docs canteen/wallet/*.java
Loading source file canteen/wallet/InsufficientBalanceException.java...
Loading source file canteen/wallet/Wallet.java...
Constructing Javadoc information...
...
Generating docs/canteen/wallet/Wallet.html...
canteen/wallet/Wallet.java:4: warning: use of default constructor, which does not provide a comment
public class Wallet {
       ^
canteen/wallet/Wallet.java:15: warning: no comment
    public long balance() { return balance; }
                ^
...
2 warnings

Document what a caller needs (rules, units, what is thrown), not how the inside works.

Common mistakes

Mistake What you see (real) Why Fix
Returning -1 for failure Thali served to Asha / Wallet balance: Rs 100 Error codes are easy to ignore Throw an exception
Accepting null in a constructor NullPointerException: Cannot invoke "String.toUpperCase()" ... in Bill.print Fails far from the cause Guard clauses, requireNonNull
Catching by message text Sorry, something went wrong after a message was reworded Code depends on human text Domain exception types
catch (Exception e) { } Nothing: the error vanishes Swallowed exception Catch specific types, or let it go up
Integer.parseInt("two") NumberFormatException: For input string: "two" Unvalidated outside input Validate at the boundary
A switch missing a Result case error: the switch statement does not cover all possible input values Forgot the failure case Handle Err too
Returning null from a finder Cannot invoke "java.lang.Long.longValue()" because the return value of "Main.priceOf(String)" is null Hidden "no value" Return Optional
Returning your real list [Chai, Masala dosa, Paneer tikka] total Rs 95 Leaks mutable state List.copyOf(...)
Importing another package's helper WalletRepository is not public in canteen.wallet; cannot be accessed from outside package Reaching into a feature's insides Use its public service

Mini project: a canteen table booking

Rules: a table has a capacity; a booking has a name and 1-6 seats; a person books once; refuse a booking that doesn't fit and say how many seats are left. It uses everything from the episode: guard clauses, a domain exception hierarchy with data, Optional, a read-only copy and a final class.

import java.util.*;

/** Thrown for any problem with a table booking. */
abstract class BookingException extends RuntimeException {
    BookingException(String message) { super(message); }
}
class TableFullException extends BookingException {
    final int seatsLeft;
    TableFullException(int seatsLeft, int wanted) {
        super("only " + seatsLeft + " seats left, wanted " + wanted);
        this.seatsLeft = seatsLeft;
    }
}
class DuplicateBookingException extends BookingException {
    DuplicateBookingException(String name) { super(name + " has already booked"); }
}

record Booking(String name, int seats) {
    Booking {
        Objects.requireNonNull(name, "name");
        if (name.isBlank()) throw new IllegalArgumentException("name is blank");
        if (seats < 1 || seats > 6) throw new IllegalArgumentException("seats must be 1 to 6: " + seats);
    }
}

final class Table {
    private final int capacity;
    private final List<Booking> bookings = new ArrayList<>();
    Table(int capacity) {
        if (capacity < 1) throw new IllegalArgumentException("capacity must be positive: " + capacity);
        this.capacity = capacity;
    }
    void book(Booking b) {
        Objects.requireNonNull(b, "booking");
        if (find(b.name()).isPresent()) throw new DuplicateBookingException(b.name());
        int left = capacity - seatsTaken();
        if (b.seats() > left) throw new TableFullException(left, b.seats());
        bookings.add(b);
    }
    Optional<Booking> find(String name) {
        return bookings.stream().filter(x -> x.name().equals(name)).findFirst();
    }
    List<Booking> bookings() { return List.copyOf(bookings); }
    int seatsTaken() { return bookings.stream().mapToInt(Booking::seats).sum(); }
}

public class Main {
    static void tryBook(Table t, String name, int seats) {
        try {
            t.book(new Booking(name, seats));
            System.out.println("booked: " + name + " x" + seats);
        } catch (TableFullException e) {
            System.out.println("full: " + e.getMessage() + " (offer " + e.seatsLeft + ")");
        } catch (BookingException | IllegalArgumentException e) {
            System.out.println("refused: " + e.getMessage());
        }
    }
    public static void main(String[] args) {
        Table t = new Table(8);
        tryBook(t, "Asha", 4);
        tryBook(t, "Ravi", 3);
        tryBook(t, "Neha", 2);
        tryBook(t, "Asha", 1);
        tryBook(t, "Priya", 0);
        System.out.println("Ravi's booking: " + t.find("Ravi").map(Booking::seats).orElse(0) + " seats");
        System.out.println("Meena's booking: " + t.find("Meena").map(Booking::seats).orElse(0) + " seats");
        System.out.println(t.bookings() + ", " + t.seatsTaken() + " of 8 seats taken");
    }
}

Output (real):

booked: Asha x4
booked: Ravi x3
full: only 1 seats left, wanted 2 (offer 1)
refused: Asha has already booked
refused: seats must be 1 to 6: 0
Ravi's booking: 3 seats
Meena's booking: 0 seats
[Booking[name=Asha, seats=4], Booking[name=Ravi, seats=3]], 7 of 8 seats taken

Practice

1. A method int findSeat(String name) returns -1 when the person has no seat. Name two problems and a better signature.

Answer

Callers can ignore -1 and use it as a seat number, and -1 is mixed with real results. Better: Optional<Integer> findSeat(String name) (no reason needed), or throw a domain exception if a missing seat is a bug.

2. Which exception fits each case? (a) withdraw(-50) (b) calling start() on a game that already started (c) a null customer name.

Answer

(a) IllegalArgumentException (bad argument) (b) IllegalStateException (wrong state) (c) NullPointerException via Objects.requireNonNull(name, "name").

3. Write guard clauses for a Student(String roll, int age) constructor: roll like CS101, age 15 to 60.

4. Turn a null-returning finder into Optional, and make a list getter safe.

Answer to 3 and 4 (run for real)
import java.util.*;

class Student {                                  // practice 3: guard clauses
    private final String roll; private final int age;
    Student(String roll, int age) {
        Objects.requireNonNull(roll, "roll");
        if (!roll.matches("[A-Z]{2}\\d{3}")) throw new IllegalArgumentException("bad roll number: " + roll);
        if (age < 15 || age > 60) throw new IllegalArgumentException("age out of range: " + age);
        this.roll = roll; this.age = age;
    }
    public String toString() { return roll + " (" + age + ")"; }
}
class Classroom {                                // practice 4: Optional + copies
    private final Map<String, Student> byRoll = new HashMap<>();
    private final List<String> notices = new ArrayList<>();
    void add(String roll, Student s) { byRoll.put(roll, s); }
    Optional<Student> find(String roll) { return Optional.ofNullable(byRoll.get(roll)); }
    void post(String notice) { notices.add(Objects.requireNonNull(notice, "notice")); }
    List<String> notices() { return List.copyOf(notices); }
}
public class Main {
    public static void main(String[] args) {
        Classroom c = new Classroom();
        c.add("CS101", new Student("CS101", 19));
        System.out.println(c.find("CS101").map(Student::toString).orElse("none"));
        System.out.println(c.find("CS999").map(Student::toString).orElse("none"));
        c.post("Lab moved to room 4");
        try { c.notices().clear(); } catch (UnsupportedOperationException e) { System.out.println("notices are read-only"); }
        System.out.println(c.notices());
        try { new Student("cs-1", 19); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); }
        try { new Student("CS102", 7); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); }
    }
}
CS101 (19)
none
notices are read-only
[Lab moved to room 4]
bad roll number: cs-1
age out of range: 7

5. Design an exception hierarchy for a cinema booking module.

Answer

BookingException extends RuntimeException (the base), with SeatTakenException (field: seat), ShowFullException (field: seatsLeft), ShowStartedException (field: startTime). Callers catch a specific child to react, or BookingException to show a general message.

6. When would you return a Result instead of throwing?

Answer

When the failure is expected and normal (a wrong coupon, an invalid form field, a seat already taken during browsing) and the caller needs the reason. Throw for bugs and broken state.

Quick quiz

A student types a coupon code at the counter; it may be wrong. What should applyCoupon do when the code is unknown? (a) return -1 (b) return null (c) return a Result: Ok(newTotal) or Err(reason) (d) System.exit(1)

Answer

(c). A wrong code is an expected, everyday failure. A Result makes the caller handle it (a switch over the sealed type won't compile without the Err case), while -1 and null are easy to ignore and System.exit stops the whole canteen app.

Interview questions

  1. Exceptions or error codes in Java? Exceptions for failures: they can't be silently ignored, aren't mixed with results, and travel up automatically. Error codes fit process exit codes and protocols (HTTP status).
  2. What is fail fast? Validate inputs at the start and throw immediately, so the error points at its cause instead of crashing later elsewhere.
  3. Checked vs unchecked exceptions for domain errors? Usually unchecked (extend RuntimeException), with a clear hierarchy; checked only when the caller must and can recover.
  4. How do you design an exception hierarchy? One base per module, specific shallow children named for the problem, data in fields, wrap low-level causes at boundaries.
  5. Why not catch Exception? It also catches bugs you didn't expect and often swallows them; catch the types you can handle.
  6. When is Optional the wrong tool? As a field or parameter type, or for collections (return an empty collection instead).
  7. Package-by-feature vs package-by-layer? By feature keeps a change in one folder and lets helpers stay package-private; by layer spreads one feature over many packages and forces public everywhere.
  8. What makes a good public API? Small, named in the domain, impossible to put into a broken state, documented, hard to misuse.

Glossary

Term Meaning, with an example
Error code A return value meaning success or a kind of failure: return -1; for "not enough money"
Exception An object thrown to signal a failure; stops the normal flow: throw new IllegalStateException(...)
throw Keyword that throws an exception object
Stack trace The list of method calls that led to an exception, newest first: at Wallet.pay(Main.java:5)
Exit code The number a program returns to the operating system: 0 = success
HTTP status code A web server's numeric answer: 404 = not found
Fail fast Check inputs first and throw at once, at the source of the mistake
Fail late Accept bad data and crash later, far away
Guard clause A check at the top of a method that throws or returns early: if (price <= 0) throw ...
Arrow code Deeply nested ifs that drift right
Happy path The normal, everything-is-fine flow through a method
Objects.requireNonNull Throws NullPointerException with your message if the value is null
IllegalArgumentException Built-in exception: the caller passed a bad argument
IllegalStateException Built-in exception: the object isn't in a state to do that
Input validation Checking outside data where it enters: a form, file or request
Boundary Where outside data enters your code
Domain The real-world area the code models: a canteen wallet
Domain exception An exception named in the domain's language: InsufficientBalanceException
Exception hierarchy A family tree of exception classes: RuntimeException → WalletException → WalletBlockedException
Checked exception Must be declared with throws and caught: IOException
Unchecked exception A RuntimeException subclass; catching is optional
Swallowing an exception Catching it and doing nothing, so the error disappears
Result type A return value that is Ok(value) or Err(reason)
Sealed interface An interface only the listed classes may implement: sealed interface Result<T> permits Ok, Err
Record pattern Takes a record apart in a switch: case Ok<Long>(Long v) ->
Exhaustive switch A switch that covers every possible case; for sealed types the compiler checks it
null A reference to no object at all
Unboxing Turning a wrapper object into a primitive: Long → long
Null-safety conventions Team rules that keep null from travelling: Optional returns, empty lists, non-null parameters
Optional<T> A box that is either empty or holds one value
Convention A rule a team agrees to follow that the compiler doesn't force
Invariant A rule that must always be true: the total matches the items
Mutable / immutable Can change / can't change after creation
Immutability by default Start with final fields, records and unmodifiable collections; allow change only where needed
Defensive copy Returning or storing a copy so outsiders can't change your data: List.copyOf(lines)
UnsupportedOperationException Thrown when you try to change an unmodifiable collection
Compact constructor A record constructor without the parameter list, used for validation
API The classes and methods other code may use
Minimal public API Exposing only what callers really need
Package A named folder of related classes: canteen.wallet
Package-private No access modifier: visible only inside the same package
Package-by-layer One package per technical layer: controller, service, repository
Package-by-feature One package per business feature: order, wallet, menu
Javadoc The JDK tool that turns /** ... */ comments into HTML documentation
Documentation comment A comment starting with /** placed right before a declaration
Block tag A Javadoc tag at the start of a line: @param, @return, @throws

Summary

  • Error codes are silent and easy to ignore; exceptions stop the flow and can't be missed.
  • Fail fast: guard clauses, Objects.requireNonNull, IllegalArgumentException, and input validation at the boundary.
  • Name failures with domain exceptions in a small hierarchy (one base per module), carrying data in fields; catch by type, never by message.
  • Use a Result type (sealed Ok/Err) for expected failures; the compiler makes callers handle both.
  • Null safety: Optional for maybe-missing results, empty collections instead of null, non-null parameters.
  • Immutable by default: final fields, records, List.copyOf; keep invariants inside the class.
  • Keep the public API minimal, arrange packages by feature so package-private can hide helpers, and document the public API with Javadoc.

Next episode: How to attack any machine-coding round: the format, time-boxing, clarifying requirements, scoping the MVP, interfaces first, in-memory repositories, a driver class and a demo main.