Result and runCatching

Result and runCatching in Kotlin: You hand a roll of film across the counter of a processing lab and come back later to collect it.

The Analogy: The Film-Processing Lab

You hand a roll of film across the counter of a processing lab and come back later to collect it. What the counter always gives you is a sealed packet -- never a shout, never a refusal to speak. Sometimes the packet holds your finished prints; sometimes it holds a fault card that reads "film fogged, no prints." Either way you receive exactly one packet, and you have to open it to learn which kind it is. Kotlin's Result<T> is that sealed packet: a single value that carries either a success with your result inside or a failure with the exception inside. The runCatching { } function is the counter itself -- it attempts the risky work and, whatever happens, hands back a packet instead of throwing an exception at you.

There are standard ways to open the packet, and which you choose depends on how much the outcome matters. You can peek and take the prints if they are there or nothing if they are not; you can accept a blank default set when there are no prints; you can hand a failed packet to a specialist who tries to salvage something; or you can insist on the prints and make a scene if the packet turns out to hold a fault card. These are Kotlin's getOrNull, getOrDefault, getOrElse, recover, and getOrThrow, along with the simple checks isSuccess and isFailure and the exceptionOrNull that reads the fault card's reason.

The lab can also do more work on your behalf, but only when the first step succeeded. Ask them to enlarge the prints and the enlargement is applied to real prints when development worked; a fault card passes straight through the enlarger untouched, still a fault card at the far end. This is what map does to a Result: it transforms the value on the success path and leaves a failure exactly as it was. And fold lets you deal with both kinds in one place -- one instruction for prints, another for the fault card -- collapsing the packet down to a single final answer.

The trap is a counter that files absolutely everything as a calm fault card, including the things that were never meant to be filed. If the building's fire alarm goes off mid-development, that is not a "no prints today" outcome -- it is an emergency that must halt the whole operation and reach you immediately. A lab that quietly stuffs the evacuation order into a fault card has hidden a signal that should never have been captured. This is the real hazard of runCatching: it catches every Throwable, including ones you must not swallow -- most sharply a coroutine's CancellationException, which keeps structured cancellation working, and fatal errors like OutOfMemoryError. Turning those into an ordinary failure result breaks the machinery that depends on them propagating.


Syntax or Core Structure

runCatching runs a block and returns a Result<T> -- success carrying the value, failure carrying the exception. You then extract a plain value with one of the getOr... functions.

fun parse(text: String): Result<Int> =
    runCatching { text.toInt() }

fun main() {
    val good = parse("42")
    val bad = parse("oops")
    println("good ok? " + good.isSuccess)
    println("good value " + good.getOrDefault(-1))
    println("bad ok? " + bad.isSuccess)
    println("bad value " + bad.getOrDefault(-1))
    println("bad has error? " + (bad.exceptionOrNull() != null))
}

Output:

good ok? true
good value 42
bad ok? false
bad value -1
bad has error? true

parse("42") runs "42".toInt() successfully, so good is a success packet: isSuccess is true and getOrDefault(-1) returns the real value 42. parse("oops") throws NumberFormatException inside the block, which runCatching captures into a failure packet: isSuccess is false and getOrDefault(-1) returns the fallback -1. The last line reads the captured exception through exceptionOrNull, which is non-null for a failure, confirming an error was stored without printing its implementation-specific message. The key point is that parse never throws -- it always returns a packet the caller opens on its own terms.


Technical Depth: Opening and Transforming a Result

The Result toolbox

Once you hold a Result<T>, these are the operations that read or transform it. Each treats the success and failure packets differently.

OperationOn successOn failure
getOrNull()the valuenull
getOrDefault(d)the valued
getOrElse { }the valuelambda result (sees the exception)
getOrThrow()the valuerethrows the exception
map { }transforms the valueunchanged failure
recover { }unchanged successturns failure into a success
fold(onS, onF)onS(value)onF(exception)

The transforming operations return a new Result, so they chain; the getOr... operations exit the Result world and hand back a plain value.

Recovering from a failure

getOrElse and recover both handle the failure path, but getOrElse yields a plain value while recover yields another Result you can keep chaining.

fun parse(text: String): Result<Int> = runCatching { text.toInt() }

fun main() {
    val a = parse("15").getOrElse { 0 }
    val b = parse("nope").getOrElse { 0 }
    val c = parse("nope").recover { -1 }.getOrThrow()
    println("a " + a)
    println("b " + b)
    println("c " + c)
}

Output:

a 15
b 0
c -1

parse("15").getOrElse { 0 } succeeds, so a is 15 and the lambda never runs. parse("nope").getOrElse { 0 } fails, so the lambda supplies 0 for b. The third line shows recovery: recover { -1 } converts the failure packet into a success packet holding -1, and getOrThrow then safely extracts -1 because the packet is now a success. recover is the tool when you want to stay in the Result pipeline after handling an error.

Transforming with map and collapsing with fold

map transforms only the success value, and fold reduces a Result to a single value by handling both cases at once.

fun parse(text: String): Result<Int> = runCatching { text.toInt() }

fun describe(text: String): String =
    parse(text)
        .map { it * 2 }
        .fold(
            onSuccess = { "doubled to " + it },
            onFailure = { "could not parse" }
        )

fun main() {
    println(describe("21"))
    println(describe("x"))
}

Output:

doubled to 42
could not parse

For "21", parse succeeds with 21, map { it * 2 } transforms it to 42, and fold takes the onSuccess branch to produce "doubled to 42". For "x", parse fails; map leaves the failure untouched (the doubling never runs), and fold takes the onFailure branch to produce "could not parse". fold is how you exit a Result while giving both outcomes an explicit answer, with no chance of forgetting the failure case.

Side effects with onSuccess and onFailure

onSuccess and onFailure run a side effect for the matching case and return the same Result, so they slot into a chain without changing the value.

fun parse(text: String): Result<Int> = runCatching { text.toInt() }

fun main() {
    parse("8")
        .onSuccess { println("got " + it) }
        .onFailure { println("failed") }
    parse("bad")
        .onSuccess { println("got " + it) }
        .onFailure { println("failed") }
}

Output:

got 8
failed

For "8", the packet is a success, so onSuccess runs and prints "got 8" while onFailure does nothing. For "bad", the packet is a failure, so onSuccess is skipped and onFailure prints "failed". Both functions return the Result unchanged, which is why they can be chained back to back and why they are ideal for logging or metrics without disturbing the value flowing through the pipeline.

map versus mapCatching

map assumes its transform cannot fail and lets any exception from the transform escape; mapCatching runs the transform inside a capture, folding a new failure back into the Result.

fun main() {
    val safe = runCatching { "10" }
        .mapCatching { it.toInt() * 2 }
    val caught = runCatching { "ten" }
        .mapCatching { it.toInt() * 2 }
    println("safe " + safe.getOrDefault(-1))
    println("caught ok? " + caught.isSuccess)
    println("caught " + caught.getOrDefault(-1))
}

Output:

safe 20
caught ok? false
caught -1

The first chain starts with the success "10"; mapCatching runs "10".toInt() * 2, which succeeds with 20, so safe.getOrDefault(-1) is 20. The second starts with the success "ten"; mapCatching runs "ten".toInt() * 2, and toInt throws NumberFormatException -- but because it is mapCatching, that exception is captured into a failure packet rather than escaping. So caught.isSuccess is false and getOrDefault(-1) yields -1. Had this been a plain map, the exception would have propagated out of the chain instead of becoming a failure result.


Real World Example: A Retry Helper

A service wants to retry flaky operations, so it builds a helper on top of runCatching: run the block, and while the Result is a failure, try again up to a limit. It looks clean and reusable.

var attempts = 0

fun loadValue(key: String): Int {
    attempts += 1
    if (key.isEmpty()) throw IllegalArgumentException("empty key")   // permanent
    return key.length
}

fun retry(times: Int, block: () -> Int): Result<Int> {
    var result = runCatching { block() }
    var n = 1
    while (result.isFailure && n < times) {
        result = runCatching { block() }        // retries on ANY failure
        n += 1
    }
    return result
}

fun main() {
    attempts = 0
    val ok = retry(3) { loadValue("abc") }
    println("ok = " + ok.getOrNull() + ", attempts = " + attempts)

    attempts = 0
    val bad = retry(3) { loadValue("") }
    println("bad ok? " + bad.isSuccess + ", attempts = " + attempts)
}

Output:

ok = 3, attempts = 1
bad ok? false, attempts = 3

The happy path is efficient. retry runs loadValue("abc") once, gets a success packet holding 3 (the key length), and returns immediately without retrying -- attempts is 1. For a genuinely transient failure that later succeeds, this loop would do exactly what you want.

The empty-key case reveals the flaw. loadValue("") throws IllegalArgumentException, a permanent error that will never succeed no matter how many times it runs. Yet retry keeps going because it only asks result.isFailure, burning all three attempts on an input that was invalid from the start -- attempts reaches 3 before it gives up.

The genuine design flaw is treating every failure as retryable, which follows directly from runCatching flattening all Throwables into one undifferentiated failure packet. The helper cannot tell a transient network blip from a permanent argument error -- or from a real bug, or from a coroutine's CancellationException that should abort the whole operation rather than be retried. It is the analogy's fire alarm filed as a routine fault card. The fix is to inspect what actually failed before retrying: read result.exceptionOrNull() and continue only for exception types known to be transient, while rethrowing or immediately returning for permanent errors and never retrying a CancellationException. The broader limitation is that Result deliberately erases the distinction between exception types at the API surface, so any logic that must branch on the kind of failure has to reach back into exceptionOrNull and check -- runCatching is a capture tool, not a classification tool.

Common Mistakes

  1. Using runCatching inside a coroutine without excluding CancellationException. It catches all Throwable, so it swallows the cancellation signal and breaks structured concurrency. Rethrow CancellationException or use a narrower try/catch.
  1. Treating every Result failure as retryable. runCatching erases the exception type at the surface, so retry logic that only checks isFailure retries permanent errors and bugs. Inspect exceptionOrNull first.
  1. Ignoring a Result you produced. A Result returned and never inspected silently drops the failure. Always consume it with fold, getOrElse, onFailure, or a check.
  1. Reaching for Result as a general return type across module boundaries. Result was designed for scoped, internal use; exposing it widely is discouraged. Prefer a sealed class or nullable for public APIs.
  1. Calling getOrThrow and defeating the purpose. If you immediately getOrThrow, you have converted a captured failure straight back into a thrown exception; you might as well not have wrapped it.
  1. Confusing map and mapCatching. map assumes its transform cannot fail; if the transform itself throws, use mapCatching so the new exception is captured into the Result rather than escaping.
  1. Swallowing the exception with getOrNull when you needed the reason. getOrNull discards why it failed. Use getOrElse { e -> ... } or exceptionOrNull when the failure detail matters.
  1. Wrapping pure control flow in runCatching. For expected, non-exceptional outcomes prefer ...OrNull functions or a sealed result; reserve runCatching for genuinely exception-throwing operations.
  1. Assuming a failed Result short-circuits later side effects. Only the Result-aware operations skip on failure; ordinary code after getOrDefault runs regardless. Keep failure handling inside the Result chain.

Best Practices

  • Use runCatching to turn a throwing operation into a value you can pass around, then handle both outcomes explicitly with fold.
  • In coroutines, avoid a bare runCatching around suspending calls, or rethrow CancellationException so cancellation still propagates.
  • Retry only on exception types known to be transient, inspecting exceptionOrNull rather than treating every failure alike.
  • Keep Result for internal, scoped error handling; expose sealed classes or nullables at public API boundaries.
  • Prefer getOrElse and recover over getOrThrow when you have a sensible fallback, so failures do not become thrown exceptions again.
  • Use mapCatching when a transform can itself fail, keeping the new exception inside the Result.
  • Chain map, recover, and fold to build a clear success-or-failure pipeline instead of nesting try/catch blocks.
  • Never leave a Result uninspected; an unconsumed failure is a silently dropped error.

Practice Exercises

  1. Write a fun safeParse(s: String): Result<Int> using runCatching, and print the outcome of a valid and an invalid input using fold with distinct success and failure messages.
  1. Chain map and getOrElse on a parsed Result to double the value on success and yield a default on failure, confirming both paths.
  1. Reproduce the retry flaw: build a retry loop that continues on any isFailure, show it burns all attempts on a permanent IllegalArgumentException, then fix it to inspect exceptionOrNull and stop retrying permanent errors.
  1. Use recover to convert a failed Result<Int> into a success holding a sentinel value, then getOrThrow it and confirm no exception is thrown.