Designing an Exception Hierarchy

Designing an Exception Hierarchy in Kotlin: When something goes wrong in a modern car, the fault is not reported as a single vague warning lamp -- it is…

The Analogy: The Car's Diagnostic Trouble Codes

When something goes wrong in a modern car, the fault is not reported as a single vague warning lamp -- it is recorded as a structured diagnostic trouble code. Every code shares a common shape: a category, a subsystem, and a place to attach readings. But codes are organised into families. There are powertrain codes, chassis codes, and body codes, and within powertrain there are more specific entries for a misfire on a named cylinder or a sensor reading out of range. A custom exception hierarchy is exactly this: a base exception type that establishes the common shape, and specific subtypes beneath it for the distinct failures a domain can actually produce.

The value of the family structure is that a technician can work at whichever level suits the task. Plug in a scan tool and ask for every powertrain fault, and it reports all of them because they all descend from the powertrain family -- the equivalent of catching the base exception to handle a whole category at once. Or focus on a single specific code to diagnose one named sensor, the equivalent of catching one concrete subtype. Because the codes form a tree, the same set of faults can be handled coarsely or finely without changing how they were raised.

Crucially, each code carries its own structured data rather than a bare label. A misfire code records which cylinder; an out-of-range code records the measured value and the expected band. This is what distinguishes a well-designed exception from a plain one: it holds domain fields -- the offending id, the limit that was exceeded -- so the handler can act on facts instead of parsing a sentence. And when one fault was triggered by a deeper one, the code references the underlying root fault, just as a Kotlin exception carries a cause pointing at the exception that provoked it.

The failure that leaves a mechanic guessing is the car that lights one amber "something is wrong" lamp with no code behind it. You know a fault occurred but not what, where, or why, so every repair starts with blind disassembly. In code this is throwing a bare Exception("error"): no type to catch selectively, no fields to read, forcing every caller to string-match the message. The opposite mistake is minting a distinct code for every trivial variation until the catalogue is unusable -- a separate exception class per micro-case that no handler can catch coherently. A good hierarchy sits between these: few enough types to catch as families, specific enough to carry the data a handler needs.


Syntax or Core Structure

A custom exception extends Exception (or RuntimeException) and passes a message up to the base constructor. It can add domain fields as ordinary properties.

class InsufficientFundsException(
    val requested: Int,
    val available: Int
) : Exception("need " + requested + " but only " + available + " available")

fun withdraw(balance: Int, amount: Int): Int {
    if (amount > balance) throw InsufficientFundsException(amount, balance)
    return balance - amount
}

fun main() {
    println(withdraw(100, 40))
    try {
        withdraw(100, 250)
    } catch (e: InsufficientFundsException) {
        println("short by " + (e.requested - e.available))
    }
}

Output:

60
short by 150

InsufficientFundsException extends Exception and builds its message from its two fields, requested and available, which it also keeps as readable properties. withdraw(100, 40) is within budget and returns 60. withdraw(100, 250) throws the custom exception; the catch binds it as e and reads its structured fields directly, computing the shortfall 250 minus 100 as 150. The handler acts on data carried by the exception rather than scraping the message string.


Technical Depth: Base Types, Families, and Causes

Choosing a base and shaping a family

The base you extend and the way you group subtypes both carry meaning. The table summarises the choices.

ChoiceMeaningWhen
extend Exceptiona recoverable conditioncallers are expected to handle it
extend RuntimeExceptiona programming or unchecked errorusually a bug, not caught routinely
a base exception + subtypesone family, catchable togetherrelated failures in one domain
sealed base exceptionclosed family, exhaustive whenall cases known at compile time
domain fields on the typestructured, actionable datahandlers need facts, not text

A shared base lets a caller write one catch for the whole domain, while the subtypes let another caller distinguish cases. A sealed base additionally lets a when over the caught exception be checked for exhaustiveness.

A family caught by its base

Define an open or abstract base exception and specific subtypes; catching the base handles the whole family.

abstract class OrderException(message: String) : Exception(message)

class OutOfStock(val sku: String) : OrderException("out of stock: " + sku)
class PaymentDeclined(val code: Int) : OrderException("payment declined: " + code)

fun place(step: String): String {
    when (step) {
        "stock" -> throw OutOfStock("A-100")
        "pay" -> throw PaymentDeclined(51)
        else -> return "placed"
    }
}

fun attempt(step: String): String =
    try {
        place(step)
    } catch (e: OrderException) {
        "order failed (" + e.message + ")"
    }

fun main() {
    println(attempt("go"))
    println(attempt("stock"))
    println(attempt("pay"))
}

Output:

placed
order failed (out of stock: A-100)
order failed (payment declined: 51)

attempt("go") returns "placed" with no exception. attempt("stock") throws OutOfStock (message "out of stock: A-100") and attempt("pay") throws PaymentDeclined (message "payment declined: 51"); both are caught by the one catch (e: OrderException) because they descend from OrderException, and each contributes its own message. One handler covered the whole family while each subtype still carried its own data.

Attaching a cause

Pass a triggering exception as the cause so the root failure is preserved when you rethrow at a higher level.

class RepositoryException(message: String, cause: Throwable) : Exception(message, cause)

fun readAge(raw: String): Int =
    try {
        raw.toInt()
    } catch (e: NumberFormatException) {
        throw RepositoryException("bad age field", e)
    }

fun main() {
    try {
        readAge("NaN")
    } catch (e: RepositoryException) {
        println(e.message + " / caused by NumberFormatException? " +
            (e.cause is NumberFormatException))
    }
}

Output:

bad age field / caused by NumberFormatException? true

RepositoryException accepts a cause and forwards it to the Exception(message, cause) constructor. When "NaN".toInt() throws NumberFormatException, the handler wraps it in a RepositoryException carrying that original as its cause. The outer handler reads e.message and confirms e.cause is NumberFormatException is true, so the low-level reason survives inside the higher-level exception rather than being discarded.

A sealed family with an exhaustive when

Making the base sealed closes the set of subtypes, so a when over a caught instance is checked for exhaustiveness and needs no else.

sealed class ConfigError(message: String) : Exception(message)
class MissingKey(val key: String) : ConfigError("missing " + key)
class WrongType(val key: String) : ConfigError("wrong type for " + key)

fun explain(e: ConfigError): String =
    when (e) {                       // exhaustive: no else needed
        is MissingKey -> "add key " + e.key
        is WrongType -> "fix type of " + e.key
    }

fun main() {
    println(explain(MissingKey("port")))
    println(explain(WrongType("host")))
}

Output:

add key port
fix type of host

Because ConfigError is sealed, the compiler knows its only subtypes are MissingKey and WrongType, so the when covering both is exhaustive and compiles without an else. explain(MissingKey("port")) matches the first branch and reads key to produce "add key port"; explain(WrongType("host")) matches the second for "fix type of host". The real payoff is future safety: add a third subtype and this when stops compiling until you handle it, which is exactly the guarantee an open base cannot give.


Real World Example: A Payment Exception Family

A payments module defines a family of exceptions under an open base PaymentException and a handler that decides what to tell the user. Two subtypes exist at first, and the handler uses a when with an else for anything else. Later a third subtype, FraudSuspected, is added by another part of the team.

open class PaymentException(message: String) : Exception(message)
class CardDeclined : PaymentException("card declined")
class InsufficientFunds : PaymentException("insufficient funds")
class FraudSuspected : PaymentException("fraud suspected")   // added later

fun handle(e: PaymentException): String =
    when (e) {
        is CardDeclined -> "ask for another card"
        is InsufficientFunds -> "ask for a smaller amount"
        else -> "transient error, retry later"     // catch-all
    }

fun main() {
    println(handle(CardDeclined()))
    println(handle(InsufficientFunds()))
    println(handle(FraudSuspected()))
}

Output:

ask for another card
ask for a smaller amount
transient error, retry later

The two original cases behave correctly: CardDeclined maps to "ask for another card" and InsufficientFunds to "ask for a smaller amount", each matched by its own is branch. For the failures the handler was written to know about, it does exactly the right thing.

The third line is the problem. FraudSuspected -- a failure that should block the transaction and flag it for review -- is instead reported as "transient error, retry later", inviting the customer to try again. It slid silently into the else branch because the handler has no case for it, and nothing warned the author that a new subtype had appeared.

The genuine design flaw is that PaymentException is an ordinary open base rather than a sealed one. Because the class hierarchy is open, the when (e) cannot be checked for exhaustiveness, so the compiler is happy to let unhandled subtypes fall through else -- and a security-relevant case is misclassified as a routine retry. Marking the base sealed class PaymentException closes the family: the when then must cover every subtype (or the code will not compile without an else), so the day FraudSuspected is added, every non-exhaustive when over a PaymentException becomes a compile error pointing straight at the handler that needs a new branch. The broader lesson is that an else on a when over an open exception type quietly absorbs future cases; a sealed hierarchy turns that silent absorption into a compile-time prompt, which is precisely what you want for a set of failures whose handling must stay complete.

Common Mistakes

  1. Throwing a bare Exception("..."). A generic exception has no type to catch selectively and no fields to read, forcing callers to string-match the message. Define a named type carrying the data a handler needs.
  1. Forgetting to forward the message or cause to the base. class MyEx : Exception() leaves message null; class MyEx(m: String) : Exception(m) sets it. When wrapping, pass the original as cause so it is not lost.
  1. Leaving an exception family open when a when handles it. Without sealed, a when over the caught base cannot be exhaustive, so newly added subtypes silently fall into else and are mishandled.
  1. Extending RuntimeException for recoverable conditions. Unchecked-style exceptions signal bugs; a condition callers should handle reads more clearly as an Exception subtype named for the domain.
  1. Over-splitting the hierarchy. A distinct class for every micro-variation produces a catalogue no handler can catch coherently. Group related failures under one family and distinguish with fields where possible.
  1. Putting mutable state in an exception. An exception should be an immutable record of what went wrong; mutable fields invite the value to change between throw and catch. Use val properties.
  1. Encoding data only in the message string. Storing "sku=A-100" inside the message forces the handler to parse text. Expose the SKU as a typed property and build the message from it.
  1. Catching your base type too broadly for unrelated code. A base that is too high in the hierarchy (like extending Exception and catching it around a huge block) recreates the swallow-everything problem. Keep the family scoped to one domain.
  1. Not overriding toString or relying on it for logic. Do not branch on an exception's rendered string; branch on its type with is and read its fields. Reserve the message for humans.

Best Practices

  • Give each domain a small exception family under one base so callers can catch the whole category or a specific case as needed.
  • Carry structured domain data as val properties on the exception, and build the message from those fields rather than the reverse.
  • Make the base sealed when handlers use a when over it, so the compiler enforces that every case is covered.
  • Extend Exception for conditions callers are expected to handle and RuntimeException for programming errors that usually indicate bugs.
  • Always forward message and, when wrapping, cause to the base constructor so no diagnostic information is dropped.
  • Name exceptions for the failure they represent (InsufficientFundsException, OutOfStock) so a catch reads as intent.
  • Keep exceptions immutable records of a failure, free of behaviour beyond holding the facts.
  • Scope the base type to a single domain so catching it never accidentally swallows unrelated failures.

Practice Exercises

  1. Define a ValidationException(val field: String, message: String) extending Exception, throw it from a validator, and in the catch read the field property to build a targeted error message.
  1. Build a sealed ApiException with two subtypes carrying different fields, and write a when handler that the compiler forces to cover both cases without an else.
  1. Reproduce the open-base flaw: handle an open exception family with a when and else, add a third subtype, and show it falls into else. Then make the base sealed and confirm the when no longer compiles until you add the branch.
  1. Wrap a low-level NumberFormatException in a custom ParseException passing the original as cause, and confirm in the outer handler that cause is the original exception type.