androidengineers.Book a session

Exception Handling and Error Management

Result & runCatching; error mapping

article15 minMedium

A captured failure still needs a policy

runCatching returns a Result containing either a value or a throwable. Mapping and recovery should preserve distinctions the caller needs rather than converting every failure into a plausible default.

fun count(text: String): Result<Int> = runCatching {
    text.toInt().also { require(it >= 0) }
}

fun main() {
    val message = count("oops").fold(
        onSuccess = { "Count: $it" },
        onFailure = { "Invalid count" }
    )
    println(message)
}

runCatching catches Throwable, including coroutine cancellation if used around suspending work inside an inline context. For coroutine boundaries, rethrow CancellationException and catch only failures you intend to handle. map also differs from mapCatching: the latter captures exceptions thrown by its transform.

Exercise

Test successful parsing, malformed text, and negative input. Replace the display-only message with a typed validation result when separate errors are required.

Check: a successful Result containing zero must remain distinguishable from a failed parse.

Reference: Result API

YOUR LEARNING JOURNEY

0 of 110 available lessons completed

Progress saved in this browser. No account needed.
Result & runCatching; error mapping | Kotlin Core Programming | Android Engineers