0
0
Kotlinprogramming~5 mins

RunCatching for safe execution in Kotlin

Choose your learning style9 modes available
Introduction

RunCatching helps you run code safely without crashing your program. It catches errors so you can handle them nicely.

When you want to try code that might fail, like reading a file.
When calling a function that can throw an error and you want to avoid crashes.
When you want to handle success and failure separately in a clean way.
When you want to keep your program running even if something goes wrong.
When you want to log or show a friendly message if an error happens.
Syntax
Kotlin
val result = runCatching {
    // code that might throw an exception
}

result.onSuccess { value ->
    // handle success
}.onFailure { error ->
    // handle error
}

runCatching runs the code inside the curly braces and catches exceptions.

The result holds success or failure, letting you handle both cases.

Examples
This tries to convert a string to a number. If it works, it prints the number. If it fails, it prints the error.
Kotlin
val result = runCatching {
    "123".toInt()
}

result.onSuccess { println("Number: $it") }
      .onFailure { println("Error: ${it.message}") }
This tries to convert a non-number string, which causes an error. The error message is printed.
Kotlin
val result = runCatching {
    "abc".toInt()
}

result.onSuccess { println("Number: $it") }
      .onFailure { println("Error: ${it.message}") }
This tries to access an invalid list index. If it fails, it returns -1 instead.
Kotlin
val result = runCatching {
    val list = listOf(1, 2, 3)
    list[5] // This will throw an exception
}

println(result.getOrElse { -1 })
Sample Program

This program tries to convert a string with letters to a number. It catches the error and prints a friendly message instead of crashing.

Kotlin
fun main() {
    val input = "100a"
    val result = runCatching {
        input.toInt()
    }

    result.onSuccess { number ->
        println("Converted number: $number")
    }.onFailure { error ->
        println("Failed to convert: ${error.message}")
    }
}
OutputSuccess
Important Notes

You can use getOrNull() to get the value or null if it failed.

Use getOrElse { defaultValue } to provide a fallback value on failure.

RunCatching helps keep your code clean by avoiding try-catch blocks everywhere.

Summary

RunCatching runs code safely and catches errors.

It lets you handle success and failure clearly.

Use it to keep your program running smoothly even if something goes wrong.