Android ● ● ● Kotlin 2.3

Kodebits Day 14: runCatching Fallback

Apr 29 2026
Capture failures as values with runCatching and recover cleanly.

What is the output?

fun risky(n: Int): Int {
  if (n == 0) error("bad")
  return 10 / n
}
fun main() {
  val out = runCatching {
    risky(0)
  }.getOrElse { -1 }
  println(out)
}


Try it in the online Kotlin Playground →

[spoiler title="Solution"]

Answer:

-1

Explanation:

risky(0) throws, runCatching captures it, and getOrElse returns -1.

[/spoiler]


Further Reading