๐ŸŽ“ A1Learner
๐Ÿ”
0 of 37 lessons completed

Kotlin Run Catching

runCatching runs a block and holds either its result or the exception it threw. Caller code then picks a value, a fallback, or a side effect for each case.

getOrElse gives a fallback

The first parse succeeds and getOrElse returns the stored number. The second parse fails and getOrElse returns the fallback from its block.

fun main() {
    val result = runCatching { "42".toInt() }
    println(result.getOrElse { -1 })
    val bad = runCatching { "abc".toInt() }
    println(bad.getOrElse { -1 })
}

onSuccess and onFailure chain

Each chain runs exactly one of its two blocks. The good division prints its result line and the bad division prints its failure line.

fun main() {
    val zero = 0
    runCatching { 10 / 2 }
        .onSuccess { println("Result $it") }
        .onFailure { println("Failed") }
    runCatching { 10 / zero }
        .onSuccess { println("Result $it") }
        .onFailure { println("Failed") }
}

getOrDefault on a parse

parseScore reads digits with toInt inside runCatching. Text with no digits falls back to the default value 0.

fun parseScore(text: String): Int {
    return runCatching { text.toInt() }.getOrDefault(0)
}

fun main() {
    println(parseScore("17"))
    println(parseScore("many"))
}

fold picks one of two blocks

fold runs its first block for a success and its second block for a failure. Each Result prints exactly one line from its matching block.

fun main() {
    val good = runCatching { "8".toInt() }
    println(good.fold({ "Value $it" }, { "No value" }))
    val bad = runCatching { "x".toInt() }
    println(bad.fold({ "Value $it" }, { "No value" }))
}

Example

fun loadLevel(text: String): Int {
    val parsed = runCatching { text.toInt() }
        .onFailure { println("Bad level text") }
        .getOrElse { 1 }
    return parsed
}

fun main() {
    println(loadLevel("3"))
    println(loadLevel("high"))
}

Key points

  • runCatching returns a Result that holds a value or a failure.
  • getOrElse returns the stored value or the result of its block for a failure.
  • onSuccess runs its block only for a success and onFailure only for a failure.
  • getOrDefault returns the stored value or a fixed default for a failure.
  • fold takes one block for success and one block for failure and returns the result of the block that runs.

In this example, loadLevel parses its text inside runCatching. The text 3 parses cleanly, so no failure line prints and the value 3 comes back. The word high fails, so onFailure prints Bad level text and getOrElse supplies the fallback 1.

Note

The calls on a Result can chain, and each call returns a Result or a value for the next step.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Kotlin Playground

Exercise

A Result holds a failure. What does getOrElse { 9 } return for it?