Error Handling - Result, Exceptions and Recovery

Article · 2:00

When to throw, when to return a type, and how cancellation differs from failure.

Kotlin has exceptions but no checked exceptions. Nothing forces a caller to handle anything, which removes Java's empty-catch-block problem and replaces it with a different responsibility: the API author must make failure visible some other way.

The usual answer is to model failure in the return type. A sealed hierarchy from level two is the most explicit form, and the standard library's Result is the ready-made version: runCatching captures success or failure, and getOrElse, getOrNull, map and recover work with it without ever unwrapping to a try block. The rule of thumb is to throw for programmer errors - a broken precondition, an impossible state - and to return a type for expected failures such as a network timeout.

Kotlin provides three precondition functions that make intent clear and messages useful. require validates arguments and throws IllegalArgumentException. check validates state and throws IllegalStateException. error throws immediately with a message.

One coroutine-specific trap deserves emphasis. Cancellation is implemented by throwing CancellationException, so a bare catch (e: Exception) inside a coroutine swallows cancellation and breaks structured concurrency. Catch specific types, or rethrow CancellationException explicitly.

data class Account(val id: Int, val balance: Int)

fun withdraw(account: Account, amount: Int): Account {
    require(amount > 0) { "amount must be positive, was $amount" }
    check(account.balance >= amount) { "insufficient funds" }
    return account.copy(balance = account.balance - amount)
}

fun parsePort(raw: String): Result<Int> = runCatching {
    val port = raw.toInt()
    require(port in 1..65535) { "port out of range: $port" }
    port
}

fun main() {
    println(withdraw(Account(1, 100), 30))      // balance 70

    // Result keeps the failure in the type rather than in control flow
    println(parsePort("8080").getOrNull())      // 8080
    println(parsePort("nope").getOrElse { -1 }) // -1
    parsePort("99999")
        .onFailure { println("rejected: ${it.message}") }
}

Discussion

No questions on this topic yet. Sign in to ask the first one.