Error Handling in Object Design
Error handling is usually taught as syntax: try, catch, finally, raise. In object design it's something bigger. The errors a class can produce are part of its interface, as much as its method names and return types. A caller has to know what can go wrong, which failures they're expected to handle, and what state the object is left in afterwards. Get that wrong, and you get the familiar symptoms: NullPointerException three layers from the cause, a booking half-saved after a failed payment, a catch (Exception e) {} swallowing a real bug, or an API that returns -1 for "not found" and -2 for "not allowed."
This page treats error handling as a design topic. It starts by separating the three kinds of failure, because each needs different treatment. Then it covers invariants and design by contract, failing fast, the choice between exceptions and result types, Java's checked versus unchecked debate, error hierarchies and translating exceptions between layers, validation at boundaries, and null handling with Optional and the Null Object pattern.
Every sample was run with Java 24, Python 3.12 and TypeScript 5.8 (tsc --strict, then tsx). Java samples use a small check helper so they fail without the -ea flag.
1. Three kinds of failure
Not all errors are alike, and most error-handling mistakes come from treating them as if they were.
| Kind | What it means | Examples | Who should handle it | Typical mechanism |
|---|---|---|---|---|
| Programmer error (bug) | Code called something wrongly: a broken precondition | null where a value is required, negative quantity, index out of range, calling ship() on an unpaid order | Nobody at runtime. Fix the code | Unchecked exception, fail fast |
| Domain failure (expected outcome) | The request was valid, but the business says no | Seat already taken, insufficient funds, coupon expired, username in use | The immediate caller, usually by showing the user a message | Result type, or a specific domain exception |
| Environmental failure | Something outside the program failed | Database down, network timeout, disk full, payment provider error | Somewhere up the stack: retry, fall back or report | Exception, translated at layer boundaries |
The distinction drives most of the decisions on this page:
- Bugs should crash loudly and early, with a message that points at the cause. Catching them and carrying on just moves the crash somewhere harder to debug.
- Domain failures are not exceptional. A sold-out show is a normal day for a ticketing system. The caller must handle them, so make them visible in the signature, through a result type or a documented exception.
- Environmental failures are unpredictable and usually not handleable where they occur. A repository can't fix a dead database. Let them propagate, translated into terms that make sense at each layer, to a place that can retry or report.
Ask "who can do something about this?"
The right place to handle an error is the place that can make a decision about it. If the method that detects a problem can't fix it, it should report it clearly and let it travel. Catching an exception you can't handle, just to log it and rethrow, usually adds noise and duplicate log lines.
2. Invariants and design by contract
Bertrand Meyer's Design by Contract, introduced with the Eiffel language in the 1980s and set out in Object-Oriented Software Construction (1988), gives the vocabulary:
- A precondition is what a method requires of its caller: "
amountis positive." - A postcondition is what a method guarantees on return: "the balance has decreased by
amount." - A class invariant is what's true of every instance whenever no method is running: "the balance is never negative."
The invariant is the most important of the three for object design. It's the reason encapsulation exists. If the fields were public, nothing could guarantee the invariant. With private fields, a class can establish its invariant in the constructor and preserve it in every method, so every object you hold is valid.
That gives two rules:
- The constructor must establish the invariant or throw. No half-built objects, no
init()method callers might forget. - Every public method must preserve the invariant, even when it fails. If a method throws halfway through, the object must still be valid. The strongest form, the strong exception guarantee in C++ terminology, is "all or nothing": either the operation completes, or the object is exactly as it was.
The easiest way to get the strong guarantee is check everything, then change everything. Validate all preconditions before the first mutation.
// ---------- before: mutate first, check later ----------
final class AccountBefore {
long balance; // anyone can set anything
AccountBefore(long opening) { balance = opening; }
static void transfer(AccountBefore from, AccountBefore to, long amount) {
from.balance -= amount;
to.balance += amount;
if (from.balance < 0) throw new IllegalStateException("insufficient funds"); // too late
}
}
// ---------- after: invariant established in the constructor, checked before any change ----------
final class Account {
private final String id;
private long balance; // invariant: balance >= 0
Account(String id, long opening) {
if (id == null || id.isBlank()) throw new IllegalArgumentException("id required");
if (opening < 0) throw new IllegalArgumentException("opening balance must be >= 0, was " + opening);
this.id = id;
this.balance = opening;
}
long balance() { return balance; }
void deposit(long amount) {
requirePositive(amount);
balance = Math.addExact(balance, amount);
}
void withdraw(long amount) {
requirePositive(amount);
if (amount > balance) throw new InsufficientFunds(id, amount, balance);
balance -= amount;
}
/** All or nothing: either both balances change, or neither does. */
static void transfer(Account from, Account to, long amount) {
if (from == to) throw new IllegalArgumentException("cannot transfer to the same account");
from.withdraw(amount); // throws before any change if it can't succeed
to.deposit(amount); // can't fail for a positive amount, short of overflow
}
private static void requirePositive(long amount) {
if (amount <= 0) throw new IllegalArgumentException("amount must be positive, was " + amount);
}
}
final class InsufficientFunds extends RuntimeException {
final long requested, available;
InsufficientFunds(String id, long requested, long available) {
super("account " + id + ": requested " + requested + ", available " + available);
this.requested = requested; this.available = available;
}
}
class InvariantDemo {
static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }
public static void main(String[] args) {
AccountBefore a = new AccountBefore(100), b = new AccountBefore(0);
try { AccountBefore.transfer(a, b, 500); } catch (IllegalStateException expected) { }
check(a.balance == -400 && b.balance == 500, "before: the error left both accounts corrupted");
Account x = new Account("x", 100), y = new Account("y", 0);
try { Account.transfer(x, y, 500); check(false, "should fail"); }
catch (InsufficientFunds e) { check(e.available == 100, "structured details"); }
check(x.balance() == 100 && y.balance() == 0, "after: nothing changed");
Account.transfer(x, y, 40);
check(x.balance() == 60 && y.balance() == 40, "after: success moves money");
try { new Account("z", -1); check(false, "invalid opening"); } catch (IllegalArgumentException expected) { }
System.out.println("invariant held through a failed transfer");
}
}
# ---------- before: mutate first, check later ----------
class AccountBefore:
def __init__(self, opening: int) -> None:
self.balance = opening
def transfer_before(src: AccountBefore, dst: AccountBefore, amount: int) -> None:
src.balance -= amount
dst.balance += amount
if src.balance < 0:
raise RuntimeError("insufficient funds") # too late
# ---------- after: invariant established in the constructor, checked before any change ----------
class InsufficientFunds(Exception):
def __init__(self, account_id: str, requested: int, available: int) -> None:
super().__init__(f"account {account_id}: requested {requested}, available {available}")
self.requested, self.available = requested, available
class Account:
def __init__(self, account_id: str, opening: int) -> None:
if not account_id:
raise ValueError("id required")
if opening < 0:
raise ValueError(f"opening balance must be >= 0, was {opening}")
self._id = account_id
self._balance = opening # invariant: balance >= 0
@property
def balance(self) -> int:
return self._balance
def deposit(self, amount: int) -> None:
_require_positive(amount)
self._balance += amount
def withdraw(self, amount: int) -> None:
_require_positive(amount)
if amount > self._balance:
raise InsufficientFunds(self._id, amount, self._balance)
self._balance -= amount
def _require_positive(amount: int) -> None:
if amount <= 0:
raise ValueError(f"amount must be positive, was {amount}")
def transfer(src: Account, dst: Account, amount: int) -> None:
"""All or nothing: either both balances change, or neither does."""
if src is dst:
raise ValueError("cannot transfer to the same account")
src.withdraw(amount)
dst.deposit(amount)
a, b = AccountBefore(100), AccountBefore(0)
try:
transfer_before(a, b, 500)
except RuntimeError:
pass
assert (a.balance, b.balance) == (-400, 500) # corrupted
x, y = Account("x", 100), Account("y", 0)
try:
transfer(x, y, 500)
raise AssertionError("should fail")
except InsufficientFunds as e:
assert e.available == 100
assert (x.balance, y.balance) == (100, 0)
transfer(x, y, 40)
assert (x.balance, y.balance) == (60, 40)
print("invariant held through a failed transfer")
function check(ok: boolean, what: string): void {
if (!ok) throw new Error(what);
}
// ---------- before: mutate first, check later ----------
class AccountBefore { constructor(public balance: number) {} }
function transferBefore(from: AccountBefore, to: AccountBefore, amount: number): void {
from.balance -= amount;
to.balance += amount;
if (from.balance < 0) throw new Error("insufficient funds"); // too late
}
// ---------- after: invariant established in the constructor, checked before any change ----------
class InsufficientFunds extends Error {
constructor(id: string, readonly requested: number, readonly available: number) {
super(`account ${id}: requested ${requested}, available ${available}`);
this.name = "InsufficientFunds";
}
}
const requirePositive = (amount: number): void => {
if (!Number.isSafeInteger(amount) || amount <= 0) throw new RangeError(`amount must be a positive integer, was ${amount}`);
};
class Account {
#balance: number; // invariant: a non-negative integer
constructor(readonly id: string, opening: number) {
if (!id) throw new RangeError("id required");
if (!Number.isSafeInteger(opening) || opening < 0) throw new RangeError(`bad opening balance ${opening}`);
this.#balance = opening;
}
get balance(): number { return this.#balance; }
deposit(amount: number): void { requirePositive(amount); this.#balance += amount; }
withdraw(amount: number): void {
requirePositive(amount);
if (amount > this.#balance) throw new InsufficientFunds(this.id, amount, this.#balance);
this.#balance -= amount;
}
/** All or nothing: either both balances change, or neither does. */
static transfer(from: Account, to: Account, amount: number): void {
if (from === to) throw new RangeError("cannot transfer to the same account");
from.withdraw(amount);
to.deposit(amount);
}
}
const a = new AccountBefore(100), b = new AccountBefore(0);
try { transferBefore(a, b, 500); } catch { /* expected */ }
check(a.balance === -400 && b.balance === 500, "before: corrupted");
const x = new Account("x", 100), y = new Account("y", 0);
let available = -1;
try { Account.transfer(x, y, 500); } catch (e) { if (e instanceof InsufficientFunds) available = e.available; }
check(available === 100 && x.balance === 100 && y.balance === 0, "after: nothing changed");
Account.transfer(x, y, 40);
check(x.balance === 60 && y.balance === 40, "after: success moves money");
console.log("invariant held through a failed transfer");
Notice that InsufficientFunds carries structured data (requested and available amounts), not just a message. A caller that wants to show "you can transfer up to 100.00" doesn't have to parse a string.
2.1 Preconditions in practice
You don't need a contracts library. In practice:
- Check preconditions on public methods and throw
IllegalArgumentException(Java),ValueErrororTypeError(Python) orRangeErrororTypeError(TypeScript) with a message that names the parameter and the bad value. - Use the type system to make preconditions disappear. A method taking
Moneydoesn't need to check that the amount has a currency. A method takingTimeRangedoesn't need to check that end is after start. The value object checked it once. See Immutability & Value Objects. - Don't re-check in private methods what the public method already guaranteed. Private methods can rely on their callers, which are all inside the class.
- Java's
assertis disabled by default (-eaenables it), so don't use it for checks that must run in production. It's fine for internal sanity checks of your own logic.
3. Fail fast
Jim Shore's 2004 IEEE Software column "Fail Fast" made the case simply: when something is wrong, stop immediately and say so clearly. The alternative, "failing slow", lets a bad value travel through the system until it causes a failure somewhere unrelated. Debugging then means working backwards from the symptom to the cause, which might be in a different class, a different request, or a configuration file read hours earlier.
The most valuable place to fail fast is construction. A misconfigured object that throws when it's built points straight at the configuration. One that's built successfully and misbehaves later points nowhere.
import java.util.function.*;
// ---------- before: accepts nonsense, fails far away ----------
final class RetryBefore {
private final int maxAttempts;
RetryBefore(int maxAttempts) { this.maxAttempts = maxAttempts; }
<T> T run(Supplier<T> op) {
RuntimeException last = null;
for (int i = 0; i < maxAttempts; i++) {
try { return op.get(); } catch (RuntimeException e) { last = e; }
}
if (last != null) throw last;
return null; // maxAttempts = 0: never ran, returns null
}
}
// ---------- after: rejects nonsense at construction, with a message that names the cause ----------
final class Retry {
private final int maxAttempts;
Retry(int maxAttempts) {
if (maxAttempts < 1) throw new IllegalArgumentException("maxAttempts must be >= 1, was " + maxAttempts);
this.maxAttempts = maxAttempts;
}
<T> T run(Supplier<T> op) {
RuntimeException last = null;
for (int i = 0; i < maxAttempts; i++) {
try { return op.get(); } catch (RuntimeException e) { last = e; }
}
throw last; // non-null: the loop ran at least once
}
}
class FailFastDemo {
static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }
public static void main(String[] args) {
RetryBefore misconfigured = new RetryBefore(0); // built fine from a bad config value
String name = misconfigured.run(() -> "ana"); // returns null, silently
try { name.length(); check(false, "expected NPE"); } // the crash happens here, far from the cause
catch (NullPointerException expected) { }
try { new Retry(0); check(false, "should reject"); }
catch (IllegalArgumentException e) { check(e.getMessage().contains("maxAttempts"), "names the cause"); }
int[] calls = {0};
String ok = new Retry(3).run(() -> { if (++calls[0] < 3) throw new IllegalStateException("flaky"); return "ana"; });
check(ok.equals("ana") && calls[0] == 3, "retries then succeeds");
System.out.println("bad configuration rejected where it was created");
}
}
from typing import Callable, TypeVar
T = TypeVar("T")
# ---------- before: accepts nonsense, fails far away ----------
class RetryBefore:
def __init__(self, max_attempts: int) -> None:
self._max = max_attempts
def run(self, op: Callable[[], T]) -> T | None:
last: Exception | None = None
for _ in range(self._max):
try:
return op()
except Exception as e:
last = e
if last:
raise last
return None # max_attempts = 0: never ran
# ---------- after: rejects nonsense at construction ----------
class Retry:
def __init__(self, max_attempts: int) -> None:
if not isinstance(max_attempts, int) or max_attempts < 1:
raise ValueError(f"max_attempts must be an int >= 1, was {max_attempts!r}")
self._max = max_attempts
def run(self, op: Callable[[], T]) -> T:
last: Exception | None = None
for _ in range(self._max):
try:
return op()
except Exception as e:
last = e
assert last is not None
raise last
name = RetryBefore(0).run(lambda: "ana")
try:
name.upper() # type: ignore[union-attr] # crash far from the cause
raise AssertionError("expected AttributeError")
except AttributeError:
pass
for bad in (0, -1, "3"):
try:
Retry(bad) # type: ignore[arg-type]
raise AssertionError(f"accepted {bad!r}")
except ValueError as e:
assert "max_attempts" in str(e)
calls = [0]
def flaky() -> str:
calls[0] += 1
if calls[0] < 3:
raise ConnectionError("flaky")
return "ana"
assert Retry(3).run(flaky) == "ana" and calls[0] == 3
print("bad configuration rejected where it was created")
function check(ok: boolean, what: string): void {
if (!ok) throw new Error(what);
}
// ---------- before: accepts nonsense, fails far away ----------
class RetryBefore {
constructor(private readonly maxAttempts: number) {}
run<T>(op: () => T): T | undefined {
let last: unknown;
for (let i = 0; i < this.maxAttempts; i++) {
try { return op(); } catch (e) { last = e; }
}
if (last !== undefined) throw last;
return undefined; // maxAttempts = 0, or NaN from a bad parse: never ran
}
}
// ---------- after: rejects nonsense at construction ----------
class Retry {
constructor(private readonly maxAttempts: number) {
if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {
throw new RangeError(`maxAttempts must be an integer >= 1, was ${maxAttempts}`);
}
}
run<T>(op: () => T): T {
let last: unknown;
for (let i = 0; i < this.maxAttempts; i++) {
try { return op(); } catch (e) { last = e; }
}
throw last;
}
}
const fromConfig = Number("three"); // NaN: a typo in a config file
const name = new RetryBefore(fromConfig).run(() => "ana");
let crashedLater = false;
try { name!.toUpperCase(); } catch { crashedLater = true; }
check(crashedLater, "before: crash far from the cause");
let message = "";
try { new Retry(fromConfig); } catch (e) { message = (e as Error).message; }
check(message.includes("maxAttempts") && message.includes("NaN"), "after: names the cause");
let calls = 0;
const ok = new Retry(3).run(() => { if (++calls < 3) throw new Error("flaky"); return "ana"; });
check(ok === "ana" && calls === 3, "retries then succeeds");
console.log("bad configuration rejected where it was created");
The TypeScript version shows a particularly common slow failure: Number("three") is NaN, and i < NaN is always false, so the loop silently never runs. The fail-fast constructor turns a mysterious "why is the name undefined?" into "maxAttempts must be an integer >= 1, was NaN."
3.1 Fail fast, but not fragile
Failing fast doesn't mean crashing the whole process for every problem. It means detecting problems at the earliest point and reporting them precisely. At the top of a request handler, a single request's bug can still be caught, logged with context, and turned into a 500 response, while other requests carry on. What you don't do is catch it deep inside, substitute a default and continue as if nothing happened.
4. Exceptions versus result types
For domain failures, the expected "no" answers, there are two main designs.
Exceptions keep the happy path clean and propagate automatically. But in Java's unchecked exceptions, Python and TypeScript, nothing in the signature tells the caller what might be thrown. They have to read documentation, or find out in production.
Result types (also called Either or Result<T, E>, standard in Rust, Swift and functional languages) make the failure part of the return type. The caller can't get the value without deciding what to do about the failure. With sealed types or discriminated unions, the compiler can check that every case is handled.
import java.util.*;
// ---------- option 1: exceptions ----------
final class SeatTakenException extends RuntimeException {
final String seat;
SeatTakenException(String seat) { super("seat " + seat + " is taken"); this.seat = seat; }
}
final class SeatMapThrowing {
private final Set<String> seats; private final Set<String> held = new HashSet<>();
SeatMapThrowing(Set<String> seats) { this.seats = Set.copyOf(seats); }
void hold(String seat) {
if (!seats.contains(seat)) throw new IllegalArgumentException("no such seat " + seat); // caller bug
if (!held.add(seat)) throw new SeatTakenException(seat); // domain failure
}
}
// ---------- option 2: a sealed result type ----------
sealed interface HoldResult permits Held, Taken, NoSuchSeat {}
record Held(String seat) implements HoldResult {}
record Taken(String seat, List<String> alternatives) implements HoldResult {}
record NoSuchSeat(String seat) implements HoldResult {}
final class SeatMap {
private final SortedSet<String> seats; private final Set<String> held = new HashSet<>();
SeatMap(Set<String> seats) { this.seats = new TreeSet<>(seats); }
HoldResult hold(String seat) {
if (!seats.contains(seat)) return new NoSuchSeat(seat);
if (!held.add(seat)) {
List<String> free = seats.stream().filter(s -> !held.contains(s)).limit(2).toList();
return new Taken(seat, free);
}
return new Held(seat);
}
}
class ResultTypeDemo {
static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }
static String message(HoldResult r) {
return switch (r) { // exhaustive: adding a fourth case won't compile until handled
case Held h -> "held " + h.seat();
case Taken t -> "taken, try " + t.alternatives();
case NoSuchSeat n -> "no seat " + n.seat();
};
}
public static void main(String[] args) {
SeatMapThrowing throwing = new SeatMapThrowing(Set.of("A1", "A2"));
throwing.hold("A1");
try { throwing.hold("A1"); check(false, "taken"); } catch (SeatTakenException e) { check(e.seat.equals("A1"), "which seat"); }
SeatMap map = new SeatMap(Set.of("A1", "A2", "A3"));
check(message(map.hold("A1")).equals("held A1"), "held");
check(message(map.hold("A1")).equals("taken, try [A2, A3]"), "taken with alternatives");
check(message(map.hold("Z9")).equals("no seat Z9"), "unknown");
System.out.println(message(map.hold("A1")));
}
}
from dataclasses import dataclass
# ---------- option 1: exceptions ----------
class SeatTaken(Exception):
def __init__(self, seat: str) -> None:
super().__init__(f"seat {seat} is taken")
self.seat = seat
class SeatMapThrowing:
def __init__(self, seats: set[str]) -> None:
self._seats, self._held = frozenset(seats), set[str]()
def hold(self, seat: str) -> None:
if seat not in self._seats:
raise ValueError(f"no such seat {seat}") # caller bug
if seat in self._held:
raise SeatTaken(seat) # domain failure
self._held.add(seat)
# ---------- option 2: a closed set of result types ----------
@dataclass(frozen=True)
class Held:
seat: str
@dataclass(frozen=True)
class Taken:
seat: str
alternatives: tuple[str, ...]
@dataclass(frozen=True)
class NoSuchSeat:
seat: str
HoldResult = Held | Taken | NoSuchSeat
class SeatMap:
def __init__(self, seats: set[str]) -> None:
self._seats, self._held = sorted(seats), set[str]()
def hold(self, seat: str) -> HoldResult:
if seat not in self._seats:
return NoSuchSeat(seat)
if seat in self._held:
return Taken(seat, tuple(s for s in self._seats if s not in self._held)[:2])
self._held.add(seat)
return Held(seat)
def message(result: HoldResult) -> str:
match result: # a type checker can flag a missing case via assert_never
case Held(seat):
return f"held {seat}"
case Taken(_, alternatives):
return f"taken, try {list(alternatives)}"
case NoSuchSeat(seat):
return f"no seat {seat}"
throwing = SeatMapThrowing({"A1", "A2"})
throwing.hold("A1")
try:
throwing.hold("A1")
raise AssertionError("expected SeatTaken")
except SeatTaken as e:
assert e.seat == "A1"
seat_map = SeatMap({"A1", "A2", "A3"})
assert message(seat_map.hold("A1")) == "held A1"
assert message(seat_map.hold("A1")) == "taken, try ['A2', 'A3']"
assert message(seat_map.hold("Z9")) == "no seat Z9"
print(message(seat_map.hold("A1")))
function check(ok: boolean, what: string): void {
if (!ok) throw new Error(what);
}
// ---------- option 1: exceptions ----------
class SeatTaken extends Error {
constructor(readonly seat: string) { super(`seat ${seat} is taken`); this.name = "SeatTaken"; }
}
class SeatMapThrowing {
private readonly held = new Set<string>();
constructor(private readonly seats: ReadonlySet<string>) {}
hold(seat: string): void {
if (!this.seats.has(seat)) throw new RangeError(`no such seat ${seat}`); // caller bug
if (this.held.has(seat)) throw new SeatTaken(seat); // domain failure
this.held.add(seat);
}
}
// ---------- option 2: a discriminated union ----------
type HoldResult =
| { kind: "held"; seat: string }
| { kind: "taken"; seat: string; alternatives: string[] }
| { kind: "noSuchSeat"; seat: string };
class SeatMap {
private readonly held = new Set<string>();
private readonly seats: string[];
constructor(seats: Iterable<string>) { this.seats = [...seats].sort(); }
hold(seat: string): HoldResult {
if (!this.seats.includes(seat)) return { kind: "noSuchSeat", seat };
if (this.held.has(seat)) {
return { kind: "taken", seat, alternatives: this.seats.filter((s) => !this.held.has(s)).slice(0, 2) };
}
this.held.add(seat);
return { kind: "held", seat };
}
}
function message(r: HoldResult): string {
switch (r.kind) {
case "held": return `held ${r.seat}`;
case "taken": return `taken, try ${r.alternatives.join(",")}`;
case "noSuchSeat": return `no seat ${r.seat}`;
default: {
const unreachable: never = r; // compile error here if a new kind is added and not handled
return unreachable;
}
}
}
const throwing = new SeatMapThrowing(new Set(["A1", "A2"]));
throwing.hold("A1");
let takenSeat = "";
try { throwing.hold("A1"); } catch (e) { if (e instanceof SeatTaken) takenSeat = e.seat; }
check(takenSeat === "A1", "exception carries the seat");
const map = new SeatMap(["A1", "A2", "A3"]);
check(message(map.hold("A1")) === "held A1", "held");
check(message(map.hold("A1")) === "taken, try A2,A3", "taken with alternatives");
check(message(map.hold("Z9")) === "no seat Z9", "unknown");
console.log(message(map.hold("A1")));
In the exception version, "no such seat" is treated as a caller bug, because the UI shouldn't offer seats that don't exist. In the result version, the design treats it as a domain answer instead, because a seat id might come from a stale page. Both choices are defensible. The point is to make the choice deliberately, per failure.
4.1 Choosing between them
| Use exceptions when… | Use result types when… |
|---|---|
| The failure is a bug (broken precondition) | The failure is an expected business outcome |
| The failure is environmental and can't be handled locally | The caller must decide what to do, every time |
| It needs to propagate through many layers to a handler | It's handled by the immediate caller |
| The language and its libraries are built around exceptions | There are several distinct failure cases, each with its own data |
| Performance of the failure path is irrelevant | Failures are frequent (validation of user input), and exceptions would be used for control flow |
Many designs use both: result types for expected domain outcomes at the API of the domain, exceptions for bugs and infrastructure failures. A book() method returns Booked | SoldOut | PaymentDeclined, and throws if the database is down.
Don't use exceptions for ordinary control flow
try { return Integer.parseInt(s); } catch (NumberFormatException e) { return 0; } inside a loop over user input is slow (building a stack trace isn't free) and hides intent. When a failure is common and expected, test first or return a result.
5. Checked versus unchecked exceptions
Java is the only mainstream language with checked exceptions: subclasses of Exception (but not RuntimeException) must be declared in a method's throws clause and handled or redeclared by every caller. Python, TypeScript, C#, Kotlin and Scala have only unchecked exceptions.
The original intent, as Effective Java Item 70 puts it: use checked exceptions for conditions the caller can reasonably be expected to recover from, and runtime exceptions for programming errors. In practice, checked exceptions have problems that have pushed most modern Java code towards unchecked ones:
- They don't compose with lambdas.
Function,Supplierand the stream API can't throw checked exceptions, so code wraps them in unchecked ones anyway. - They leak implementation details. A repository interface that declares
throws SQLExceptiontells every caller it's backed by SQL. Switching to a REST backend changes the signature. - They encourage swallowing. Faced with a checked exception they can't handle, developers write
catch (IOException e) {}to make the compiler stop complaining. - The "recoverable" line is blurry. Whether a caller can recover depends on the caller, not the thrower.
A practical modern position for LLD:
| Failure | Java | Python and TypeScript |
|---|---|---|
| Programmer error | IllegalArgumentException, IllegalStateException, NullPointerException | ValueError, TypeError, RangeError |
| Domain failure | A result type, or a specific unchecked domain exception | A result type, or a specific domain exception |
| Environmental failure | Catch the checked exception at the adapter boundary and translate it to an unchecked domain-level exception with the cause attached | Translate at the adapter boundary, chaining the cause |
6. Error hierarchies and exception translation
When you do use exceptions, design them like any other type hierarchy.
- One base type per module or domain, like
BookingException. Callers that want to handle "anything that went wrong with booking" catch that one type. - Subtypes for failures callers handle differently, not one per message.
SeatUnavailableandPaymentDeclinedlead to different user actions. Three variants of "invalid input" probably don't need three classes. - Carry data, not just text. The seat id, the requested amount, an error code for API responses. Messages are for humans and logs, and fields are for code.
- Translate at layer boundaries. Bloch's Item 73 says to throw exceptions appropriate to the abstraction. A
BookingServiceshouldn't letSQLExceptionorConnectionResetErrorescape. It catches them and throwsBookingStorageException, attaching the original as the cause so the stack trace isn't lost. - Never lose the cause.
throw new X(e.getMessage())discards the original stack trace. Usenew X(message, e)in Java,raise X(...) from ein Python, andnew X(message, { cause: e })in TypeScript.
classDiagram
class BookingException {
<<abstract>>
+String code
}
class SeatUnavailable {
+String seat
}
class PaymentDeclined {
+String reason
}
class BookingStorageException {
+Throwable cause
}
BookingException <|-- SeatUnavailable
BookingException <|-- PaymentDeclined
BookingException <|-- BookingStorageException
import java.io.IOException;
import java.util.*;
abstract class BookingException extends RuntimeException {
final String code;
BookingException(String code, String message, Throwable cause) { super(message, cause); this.code = code; }
}
final class SeatUnavailable extends BookingException {
final String seat;
SeatUnavailable(String seat) { super("SEAT_UNAVAILABLE", "seat " + seat + " is not available", null); this.seat = seat; }
}
final class PaymentDeclined extends BookingException {
PaymentDeclined(String reason) { super("PAYMENT_DECLINED", "payment declined: " + reason, null); }
}
final class BookingStorageException extends BookingException {
BookingStorageException(String message, Throwable cause) { super("STORAGE", message, cause); }
}
// The low-level store throws a checked, implementation-specific exception.
interface BookingStore { void save(String seat, String user) throws IOException; }
final class BookingService {
private final BookingStore store; private final Set<String> taken = new HashSet<>();
BookingService(BookingStore store) { this.store = store; }
void book(String seat, String user, boolean cardOk) {
if (taken.contains(seat)) throw new SeatUnavailable(seat);
if (!cardOk) throw new PaymentDeclined("card refused");
try {
store.save(seat, user);
} catch (IOException e) {
throw new BookingStorageException("could not save booking for seat " + seat, e); // translate, keep cause
}
taken.add(seat);
}
}
class HierarchyDemo {
static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }
static String handle(Runnable action) { // e.g. a controller mapping errors to responses
try { action.run(); return "201"; }
catch (SeatUnavailable e) { return "409 " + e.code + " " + e.seat; }
catch (BookingException e) { return (e instanceof BookingStorageException ? "503 " : "402 ") + e.code; }
}
public static void main(String[] args) {
BookingService ok = new BookingService((seat, user) -> {});
check(handle(() -> ok.book("A1", "ana", true)).equals("201"), "booked");
check(handle(() -> ok.book("A1", "bo", true)).equals("409 SEAT_UNAVAILABLE A1"), "taken");
check(handle(() -> ok.book("A2", "bo", false)).equals("402 PAYMENT_DECLINED"), "declined");
BookingService broken = new BookingService((seat, user) -> { throw new IOException("disk full"); });
check(handle(() -> broken.book("B1", "cy", true)).equals("503 STORAGE"), "storage");
try { broken.book("B1", "cy", true); }
catch (BookingStorageException e) { check(e.getCause().getMessage().equals("disk full"), "cause kept"); }
check(handle(() -> broken.book("B1", "cy", true)).equals("503 STORAGE"), "seat wasn't marked taken");
System.out.println("errors mapped by type, causes preserved");
}
}
class BookingError(Exception):
code = "BOOKING"
class SeatUnavailable(BookingError):
code = "SEAT_UNAVAILABLE"
def __init__(self, seat: str) -> None:
super().__init__(f"seat {seat} is not available")
self.seat = seat
class PaymentDeclined(BookingError):
code = "PAYMENT_DECLINED"
class BookingStorageError(BookingError):
code = "STORAGE"
class BookingService:
def __init__(self, save) -> None:
self._save = save
self._taken: set[str] = set()
def book(self, seat: str, user: str, card_ok: bool) -> None:
if seat in self._taken:
raise SeatUnavailable(seat)
if not card_ok:
raise PaymentDeclined("card refused")
try:
self._save(seat, user)
except OSError as e:
raise BookingStorageError(f"could not save booking for seat {seat}") from e
self._taken.add(seat)
def handle(action) -> str:
try:
action()
return "201"
except SeatUnavailable as e:
return f"409 {e.code} {e.seat}"
except BookingError as e:
return ("503 " if isinstance(e, BookingStorageError) else "402 ") + e.code
ok = BookingService(lambda seat, user: None)
assert handle(lambda: ok.book("A1", "ana", True)) == "201"
assert handle(lambda: ok.book("A1", "bo", True)) == "409 SEAT_UNAVAILABLE A1"
assert handle(lambda: ok.book("A2", "bo", False)) == "402 PAYMENT_DECLINED"
def disk_full(seat: str, user: str) -> None:
raise OSError("disk full")
broken = BookingService(disk_full)
assert handle(lambda: broken.book("B1", "cy", True)) == "503 STORAGE"
try:
broken.book("B1", "cy", True)
except BookingStorageError as e:
assert isinstance(e.__cause__, OSError) and str(e.__cause__) == "disk full"
print("errors mapped by type, causes preserved")
function check(ok: boolean, what: string): void {
if (!ok) throw new Error(what);
}
abstract class BookingError extends Error {
abstract readonly code: string;
constructor(message: string, options?: { cause?: unknown }) {
super(message, options);
this.name = new.target.name;
}
}
class SeatUnavailable extends BookingError {
readonly code = "SEAT_UNAVAILABLE";
constructor(readonly seat: string) { super(`seat ${seat} is not available`); }
}
class PaymentDeclined extends BookingError { readonly code = "PAYMENT_DECLINED"; }
class BookingStorageError extends BookingError { readonly code = "STORAGE"; }
type Save = (seat: string, user: string) => void;
class BookingService {
private readonly taken = new Set<string>();
constructor(private readonly save: Save) {}
book(seat: string, user: string, cardOk: boolean): void {
if (this.taken.has(seat)) throw new SeatUnavailable(seat);
if (!cardOk) throw new PaymentDeclined("payment declined: card refused");
try {
this.save(seat, user);
} catch (e) {
throw new BookingStorageError(`could not save booking for seat ${seat}`, { cause: e });
}
this.taken.add(seat);
}
}
function handle(action: () => void): string {
try { action(); return "201"; }
catch (e) {
if (e instanceof SeatUnavailable) return `409 ${e.code} ${e.seat}`;
if (e instanceof BookingError) return `${e instanceof BookingStorageError ? "503" : "402"} ${e.code}`;
throw e; // not ours: let it propagate
}
}
const ok = new BookingService(() => {});
check(handle(() => ok.book("A1", "ana", true)) === "201", "booked");
check(handle(() => ok.book("A1", "bo", true)) === "409 SEAT_UNAVAILABLE A1", "taken");
check(handle(() => ok.book("A2", "bo", false)) === "402 PAYMENT_DECLINED", "declined");
const broken = new BookingService(() => { throw new Error("disk full"); });
check(handle(() => broken.book("B1", "cy", true)) === "503 STORAGE", "storage");
try { broken.book("B1", "cy", true); }
catch (e) { check(e instanceof BookingStorageError && (e.cause as Error).message === "disk full", "cause kept"); }
console.log("errors mapped by type, causes preserved");
The handle function plays the role of a controller or CLI driver: the one place that knows how to turn domain errors into responses. It catches by category, using the hierarchy, and lets anything it doesn't recognise propagate. Notice also that the failed save doesn't mark the seat as taken. The service mutates its own state only after the external call succeeds, which is the "check, then change" rule from section 2 applied across a collaborator.
TypeScript error subclasses
With an ES2015 or later compile target, class X extends Error works with instanceof. With an ES5 target, it doesn't unless you call Object.setPrototypeOf(this, new.target.prototype) in the constructor, a common source of confusion in older codebases. Setting this.name makes stack traces readable.
6.1 Messages, codes and logs
An error has three audiences, and each needs something different:
- Code needs a type or a stable code to branch on. Never make callers parse message strings. Messages get reworded, translated and improved, and every
if (e.getMessage().contains("taken"))breaks when they do. - Developers need a message with context: which object, which value, what was expected. "Invalid input" is useless. "maxAttempts must be >= 1, was 0" tells you exactly where to look. Include identifiers (the seat, the account, the order), but never secrets such as passwords, full card numbers or tokens.
- End users need a friendly, actionable message in their language: "That seat was just taken. A2 and A3 are still free." That message belongs at the boundary, built from the error's type and fields, not inside the domain, which shouldn't know about UI wording or locales.
Logging follows from the same split. Log once, at the place that finally handles the error, with the full cause chain. Domain code that throws shouldn't also log, or every failure appears several times with slightly different context. Expected domain failures, like a seat being taken, usually aren't worth a warning-level log line at all. They're normal business events, and maybe worth a metric.
7. Validation at boundaries
Where should input be validated? The answer is at the boundary where untrusted data enters, and then never again, because from that point on the data is carried in types that can only hold valid values.
Alexis King's 2019 essay Parse, don't validate puts it neatly. A validator checks data and returns nothing useful (void or a boolean), so the rest of the code has to trust that someone, somewhere, called it. A parser checks data and returns a more precise type that proves the check happened. Downstream code takes the precise type and doesn't need to check again.
There's also a difference in what boundaries and domain objects should do on failure:
- At the user-facing boundary, collect all the problems and report them together. A sign-up form that says "email invalid", then on resubmission "age missing", then "password too short" is infuriating.
- Inside the domain, throw on the first broken invariant. By then, invalid input is a bug, because the boundary should have caught it.
import java.util.*;
record Email(String value) {
Email {
if (value == null || !value.matches("[^@\\s]+@[^@\\s]+\\.[^@\\s]+")) throw new IllegalArgumentException("invalid email");
}
}
record Signup(Email email, int age, String name) {
Signup {
Objects.requireNonNull(email);
if (age < 13) throw new IllegalArgumentException("age must be >= 13"); // domain: fail on first problem
if (name.isBlank()) throw new IllegalArgumentException("name required");
}
}
sealed interface Parsed permits Valid, Invalid {}
record Valid(Signup signup) implements Parsed {}
record Invalid(Map<String, String> errors) implements Parsed {}
// The boundary: untrusted strings in, either a valid domain object or every problem at once.
final class SignupForm {
static Parsed parse(Map<String, String> form) {
Map<String, String> errors = new LinkedHashMap<>();
String rawEmail = form.getOrDefault("email", "").strip();
String rawAge = form.getOrDefault("age", "").strip();
String name = form.getOrDefault("name", "").strip();
Email email = null;
try { email = new Email(rawEmail); } catch (IllegalArgumentException e) { errors.put("email", "is not a valid address"); }
int age = -1;
try { age = Integer.parseInt(rawAge); if (age < 13) errors.put("age", "must be 13 or over"); }
catch (NumberFormatException e) { errors.put("age", "must be a whole number"); }
if (name.isEmpty()) errors.put("name", "is required");
return errors.isEmpty() ? new Valid(new Signup(email, age, name)) : new Invalid(errors);
}
}
class BoundaryDemo {
static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }
public static void main(String[] args) {
Parsed bad = SignupForm.parse(Map.of("email", "ana@", "age", "twelve"));
check(bad instanceof Invalid i && i.errors().keySet().equals(Set.of("email", "age", "name")), "all problems at once");
Parsed good = SignupForm.parse(Map.of("email", " ana@x.io ", "age", "30", "name", "Ana"));
check(good instanceof Valid v && v.signup().email().value().equals("ana@x.io"), "parsed and normalised");
try { new Signup(new Email("ana@x.io"), 9, "Ana"); check(false, "domain must reject"); }
catch (IllegalArgumentException expected) { } // inside the domain, invalid data is a bug
System.out.println(bad);
}
}
import re
from dataclasses import dataclass
EMAIL = re.compile(r"[^@\s]+@[^@\s]+\.[^@\s]+")
@dataclass(frozen=True)
class Email:
value: str
def __post_init__(self) -> None:
if not EMAIL.fullmatch(self.value):
raise ValueError("invalid email")
@dataclass(frozen=True)
class Signup:
email: Email
age: int
name: str
def __post_init__(self) -> None: # domain: fail on the first problem
if self.age < 13:
raise ValueError("age must be >= 13")
if not self.name.strip():
raise ValueError("name required")
def parse_signup(form: dict[str, str]) -> Signup | dict[str, str]:
"""The boundary: untrusted strings in, a Signup or every problem at once."""
errors: dict[str, str] = {}
email: Email | None = None
try:
email = Email(form.get("email", "").strip())
except ValueError:
errors["email"] = "is not a valid address"
age = -1
try:
age = int(form.get("age", "").strip())
if age < 13:
errors["age"] = "must be 13 or over"
except ValueError:
errors["age"] = "must be a whole number"
name = form.get("name", "").strip()
if not name:
errors["name"] = "is required"
if errors or email is None:
return errors
return Signup(email, age, name)
bad = parse_signup({"email": "ana@", "age": "twelve"})
assert isinstance(bad, dict) and set(bad) == {"email", "age", "name"}
good = parse_signup({"email": " ana@x.io ", "age": "30", "name": "Ana"})
assert isinstance(good, Signup) and good.email.value == "ana@x.io"
try:
Signup(Email("ana@x.io"), 9, "Ana")
raise AssertionError("domain must reject")
except ValueError:
pass
print(bad)
function check(ok: boolean, what: string): void {
if (!ok) throw new Error(what);
}
type Email = string & { readonly __brand: "Email" };
const EMAIL = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
function toEmail(raw: string): Email {
if (!EMAIL.test(raw)) throw new RangeError("invalid email");
return raw as Email;
}
class Signup {
constructor(readonly email: Email, readonly age: number, readonly name: string) {
if (!Number.isInteger(age) || age < 13) throw new RangeError("age must be an integer >= 13"); // domain
if (!name.trim()) throw new RangeError("name required");
}
}
type Parsed = { ok: true; signup: Signup } | { ok: false; errors: Record<string, string> };
/** The boundary: untrusted input in, a Signup or every problem at once. */
function parseSignup(form: Record<string, string | undefined>): Parsed {
const errors: Record<string, string> = {};
const rawEmail = (form.email ?? "").trim();
const age = Number((form.age ?? "").trim());
const name = (form.name ?? "").trim();
if (!EMAIL.test(rawEmail)) errors.email = "is not a valid address";
if (!Number.isInteger(age)) errors.age = "must be a whole number";
else if (age < 13) errors.age = "must be 13 or over";
if (!name) errors.name = "is required";
if (Object.keys(errors).length > 0) return { ok: false, errors };
return { ok: true, signup: new Signup(toEmail(rawEmail), age, name) };
}
const bad = parseSignup({ email: "ana@", age: "twelve" });
check(!bad.ok && Object.keys(bad.errors).sort().join() === "age,email,name", "all problems at once");
const good = parseSignup({ email: " ana@x.io ", age: "30", name: "Ana" });
check(good.ok && good.signup.email === "ana@x.io", "parsed and normalised");
let rejected = false;
try { new Signup(toEmail("ana@x.io"), 9, "Ana"); } catch { rejected = true; }
check(rejected, "inside the domain, invalid data is a bug");
console.log(bad);
The domain object still validates, so a bug elsewhere can't create an invalid Signup. The boundary is the friendly layer that translates problems into messages for the user. Some duplication between the two is acceptable, because they serve different purposes and fail differently: one reports, the other protects.
8. Null handling
Tony Hoare, who introduced null references in ALGOL W in 1965, called them his "billion-dollar mistake" in a 2009 QCon talk. The problem isn't that "no value" needs representing. It's that a null can hide inside any reference type, so the type system can't tell you which references might be absent. Every dereference becomes a potential crash.
The modern tools:
| Language | Mechanism | Notes |
|---|---|---|
| Java | Optional<T> (Java 8+) | Intended for return types that may be empty. Brian Goetz, Java's language architect, has advised against using it for fields, parameters or collections |
| Java | Objects.requireNonNull | Fail fast on a null argument |
| Python | T | None with a type checker (mypy, pyright) | Plain Python doesn't enforce it at runtime. The checker flags unguarded use |
| TypeScript | strictNullChecks (part of --strict) | T | undefined must be narrowed before use. ?. and ?? help |
| All | The Null Object pattern | A real object with do-nothing or neutral behaviour, so callers need no checks at all |
Two complementary techniques fix most null problems:
- Make absence visible in the type when the caller must decide what to do. "This member might not exist" is information.
Optional<Member>orMember | Noneforces the caller to handle it. - Make absence invisible with a Null Object when there's a sensible default behaviour. "No discount" isn't a special case that every caller should handle. It's a discount of zero.
import java.util.*;
record Member(String id, String name) {}
// ---------- before: null for "not found" and for "no discount" ----------
final class LibraryBefore {
private final Map<String, Member> members = new HashMap<>();
LibraryBefore() { members.put("m1", new Member("m1", "Ana")); }
Member find(String id) { return members.get(id); } // may return null, silently
Map<String, Integer> discountPercent = new HashMap<>(Map.of("m1", 10)); // missing key -> null
long fee(String memberId, long baseCents) {
Integer pct = discountPercent.get(memberId);
return baseCents - baseCents * pct / 100; // NPE when unboxing null
}
}
// ---------- after: Optional where absence matters, a Null Object where it doesn't ----------
interface Discount { long apply(long cents); }
record PercentOff(int percent) implements Discount {
PercentOff {
if (percent < 0 || percent > 100) throw new IllegalArgumentException("percent 0..100");
}
public long apply(long cents) { return cents - cents * percent / 100; }
}
enum NoDiscount implements Discount {
INSTANCE;
public long apply(long cents) { return cents; }
}
final class Library {
private final Map<String, Member> members = new HashMap<>();
private final Map<String, Discount> discounts = new HashMap<>();
Library() { members.put("m1", new Member("m1", "Ana")); discounts.put("m1", new PercentOff(10)); }
Optional<Member> find(String id) { return Optional.ofNullable(members.get(id)); }
Discount discountFor(String memberId) { return discounts.getOrDefault(memberId, NoDiscount.INSTANCE); }
long fee(String memberId, long baseCents) { return discountFor(memberId).apply(baseCents); }
}
class NullHandlingDemo {
static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }
public static void main(String[] args) {
LibraryBefore old = new LibraryBefore();
try { old.find("m9").name(); check(false, "NPE expected"); } catch (NullPointerException expected) { }
try { old.fee("m2", 1_000); check(false, "NPE expected"); } catch (NullPointerException expected) { }
Library lib = new Library();
check(lib.find("m1").map(Member::name).orElse("guest").equals("Ana"), "present");
check(lib.find("m9").map(Member::name).orElse("guest").equals("guest"), "absent, handled by the caller");
check(lib.fee("m1", 1_000) == 900, "10% off");
check(lib.fee("m2", 1_000) == 1_000, "no discount, no null check anywhere");
System.out.println("absence handled by type or by a null object");
}
}
from dataclasses import dataclass
from typing import Protocol
@dataclass(frozen=True)
class Member:
id: str
name: str
# ---------- before: None for "not found" and for "no discount" ----------
class LibraryBefore:
def __init__(self) -> None:
self.members = {"m1": Member("m1", "Ana")}
self.discount_percent = {"m1": 10}
def find(self, member_id: str): # untyped: callers don't know it can be None
return self.members.get(member_id)
def fee(self, member_id: str, base: int) -> int:
pct = self.discount_percent.get(member_id)
return base - base * pct // 100 # TypeError when pct is None # type: ignore[operator]
old = LibraryBefore()
for broken in (lambda: old.find("m9").name, lambda: old.fee("m2", 1_000)):
try:
broken()
raise AssertionError("expected a crash")
except (AttributeError, TypeError):
pass
# ---------- after: Optional in the type where absence matters, a Null Object where it doesn't ----------
class Discount(Protocol):
def apply(self, cents: int) -> int: ...
@dataclass(frozen=True)
class PercentOff:
percent: int
def __post_init__(self) -> None:
if not 0 <= self.percent <= 100:
raise ValueError("percent 0..100")
def apply(self, cents: int) -> int:
return cents - cents * self.percent // 100
class NoDiscount:
def apply(self, cents: int) -> int:
return cents
NO_DISCOUNT = NoDiscount()
class Library:
def __init__(self) -> None:
self._members = {"m1": Member("m1", "Ana")}
self._discounts: dict[str, Discount] = {"m1": PercentOff(10)}
def find(self, member_id: str) -> Member | None: # a type checker forces callers to handle None
return self._members.get(member_id)
def fee(self, member_id: str, base: int) -> int:
return self._discounts.get(member_id, NO_DISCOUNT).apply(base)
lib = Library()
found = lib.find("m1")
assert (found.name if found else "guest") == "Ana"
missing = lib.find("m9")
assert (missing.name if missing else "guest") == "guest"
assert lib.fee("m1", 1_000) == 900 and lib.fee("m2", 1_000) == 1_000
print("absence handled by type or by a null object")
function check(ok: boolean, what: string): void {
if (!ok) throw new Error(what);
}
interface Member { readonly id: string; readonly name: string }
// ---------- before: escape hatches that hide absence ----------
const membersBefore: Record<string, Member> = { m1: { id: "m1", name: "Ana" } };
const discountBefore: Record<string, number> = { m1: 10 };
const findBefore = (id: string): Member => membersBefore[id]!; // the "!" lies to the compiler
const feeBefore = (id: string, base: number): number => base - (base * discountBefore[id]!) / 100;
let crashed = false;
try { findBefore("m9").name.toUpperCase(); } catch { crashed = true; }
check(crashed, "before: crash on a missing member");
check(Number.isNaN(feeBefore("m2", 1_000)), "before: NaN fee, no crash at all");
// ---------- after: absence in the type where it matters, a Null Object where it doesn't ----------
interface Discount { apply(cents: number): number }
const percentOff = (percent: number): Discount => {
if (!(percent >= 0 && percent <= 100)) throw new RangeError("percent 0..100");
return { apply: (c) => c - Math.floor((c * percent) / 100) };
};
const noDiscount: Discount = { apply: (c) => c };
class Library {
private readonly members = new Map<string, Member>([["m1", { id: "m1", name: "Ana" }]]);
private readonly discounts = new Map<string, Discount>([["m1", percentOff(10)]]);
find(id: string): Member | undefined { return this.members.get(id); } // strict mode forces a check
fee(id: string, base: number): number { return (this.discounts.get(id) ?? noDiscount).apply(base); }
}
const lib = new Library();
check((lib.find("m1")?.name ?? "guest") === "Ana", "present");
check((lib.find("m9")?.name ?? "guest") === "guest", "absent, handled by the caller");
check(lib.fee("m1", 1_000) === 900 && lib.fee("m2", 1_000) === 1_000, "no null checks for discounts");
console.log("absence handled by type or by a null object");
The TypeScript "before" shows how not to use a strict type checker: the non-null assertion ! silences the compiler, and the program then either crashes or, worse, quietly computes NaN. A wrong number with no exception is the slowest kind of failure.
8.1 Rules for null and Optional
- Never return
nullfor a collection. Return an empty one. Callers can loop over it without a check. - Don't use
Optionalfor fields or parameters in Java. For fields, usenullinternally behind an accessor that returnsOptional. For parameters, overload the method or accept a Null Object. - Don't call
Optional.get()without a check. Usemap,orElse,orElseThroworifPresent.get()on an emptyOptionaljust moves the crash. - Use a Null Object when "nothing" has natural behaviour: no discount, a logger that discards, an empty iterator, a guest user with no permissions. Don't use one when the caller genuinely needs to know the value is missing. A "null member" that pretends to borrow books would hide a real error.
- Reject nulls at boundaries with
Objects.requireNonNullor equivalent, so the problem surfaces where the null came in.
9. When error handling goes too far
| Over-application | Symptom | Better |
|---|---|---|
| Defensive checks everywhere | Every private method re-checks every argument for null and range | Check at public boundaries and in constructors. Trust private callers. Use types to make invalid states unrepresentable |
| Catch-all handlers | catch (Exception e) { log(e); } in business logic, so bugs are logged and the program continues in a broken state | Catch specific exceptions where you can act on them. Have one top-level handler per request or job |
| Exception class per message | InvalidEmailFormatException, EmailTooLongException, EmailMissingAtException | One exception type per different handling. Put details in fields |
| Result types for everything | Every function returns Result, including ones that can only fail on a bug | Results for expected domain outcomes. Exceptions for bugs and infrastructure |
| Optional everywhere | Optional<Optional<String>>, Optional fields, Optional parameters | Use it as a return type for "may be absent", and use Null Objects or overloads elsewhere |
| Logging and rethrowing at every layer | The same stack trace logged five times | Log once, where the error is finally handled |
| Retrying bugs | A retry wrapper around code that throws IllegalArgumentException | Retry only transient environmental failures, such as timeouts or 503 responses |
10. How it shows up in LLD interviews
Error handling is where interviewers separate "it works for the demo" from "it would survive production." Most candidates write the happy path and stop.
What strong answers include:
- Validation in constructors of value objects and entities, with clear messages. "
TimeRangethrows if end isn't after start, so every range in the system is valid." - Explicit domain failures in the API. "
book()returnsBooked,SeatTakenorPaymentDeclined" or "book()throwsSeatUnavailableException, which the controller maps to 409." Name them in the class diagram. - State consistency on failure. "If payment fails, the seat hold is released and no booking is saved." Interviewers often ask exactly this.
- No nulls in the API.
Optional<Spot>fromfindFreeSpot, empty lists rather than null, aNoDiscountdefault. - A single place that maps errors to output, such as the CLI driver in a machine-coding round.
Common follow-ups:
- "What happens if two users book the same seat?" One succeeds and one gets a domain failure. That's error handling and concurrency. See Classic Synchronization Problems.
- "What if the payment service times out?" That's environmental. Retry with a limit, or mark the booking as pending and reconcile. Never leave it half-done silently.
- "Why an exception and not a return code?" Have the three-kinds framing ready.
- "How would the API layer report these errors?" Error codes in the exception hierarchy map to HTTP statuses in one handler.
Red flags:
catch (Exception e) { e.printStackTrace(); }in domain code.- Methods returning
null,-1orfalsewith no explanation of what the failure was. - Objects that can exist in invalid states (
new Booking()followed by setters). - No mention of what happens when a collaborator fails partway through.
Say this: "Invalid arguments are bugs, so they throw immediately. Seat-taken and payment-declined are normal outcomes, so they're in the return type and the caller has to handle them. Storage failures are translated into a booking exception with the cause attached, and the booking isn't recorded unless the save succeeds."
11. Interview questions
-
"How do you decide whether to throw an exception or return an error?" Classify the failure. Programmer errors throw unchecked exceptions and fail fast. Expected domain outcomes, like a sold-out show, go in the return type or a specific documented exception so callers must handle them. Environmental failures throw and are translated at layer boundaries.
-
"What is a class invariant, and who enforces it?" A condition true of every instance between method calls, like "balance is never negative." The class enforces it: the constructor establishes it or throws, and every public method preserves it, including on failure. Encapsulation is what makes that possible.
-
"What does fail fast mean?" Detect problems at the earliest point and report them clearly, rather than letting bad values travel and cause failures somewhere unrelated. Validate in constructors and at public boundaries, and never substitute silent defaults for invalid input.
-
"How do you keep an object consistent when a method fails halfway?" Check all preconditions before the first mutation. Order operations so the ones that can fail come first. Mutate your own state only after external calls succeed. If something can still fail after mutation, compensate, or work on a copy and swap.
-
"Checked or unchecked exceptions?" Checked exceptions were meant for recoverable conditions, but they don't compose with lambdas, leak implementation details through interfaces and encourage swallowing. Most modern Java designs use unchecked exceptions for bugs and translated infrastructure failures, and result types or specific unchecked exceptions for domain outcomes.
-
"How would you design an exception hierarchy for a booking system?" A base
BookingExceptionwith an error code, and subtypes only for failures handled differently:SeatUnavailable,PaymentDeclinedandBookingStorageException. Carry structured data. Translate low-level exceptions at the boundary with the cause attached. -
"What does 'parse, don't validate' mean?" Instead of checking input and passing the raw value along, convert it into a type that can only hold valid values, like
EmailorTimeRange. Downstream code takes that type and never re-checks. Boundaries collect all problems for the user. The domain throws on the first broken invariant. -
"When should you use
Optional?" As a return type for a lookup that may legitimately find nothing. Not for fields, parameters or collections. Never callget()without checking. Prefermap,orElseandorElseThrow. -
"What's the Null Object pattern, and when is it wrong?" A real implementation of an interface with neutral behaviour, like
NoDiscountor a discarding logger, so callers don't need null checks. It's wrong when absence is meaningful to the caller, for example a missing user, where hiding the absence would mask a real error. -
"Your service catches
Exceptionand logs it. What's wrong with that?" It catches bugs along with expected failures, keeps running in a possibly inconsistent state, and usually logs the same error again at higher layers. Catch specific exceptions where you can act. Let others reach one top-level handler that logs once and returns an error.
Related pages
- Immutability, Value Objects & Defensive Copying
- Interfaces & API Design at Class Level
- Designing for Testability
- Liskov Substitution Principle, whose contract rules cover preconditions and exceptions in subtypes
- Null Object pattern
- From Nouns to Classes: aggregates and invariants
- Common LLD Mistakes: missing edge cases