How to Use runCatching in Kotlin for Safe Exception Handling
In Kotlin,
runCatching executes a block of code and catches any exceptions, returning a Result object. You can then use onSuccess and onFailure to handle the outcome without try-catch blocks.Syntax
The runCatching function takes a lambda block that might throw an exception. It returns a Result object which holds either the successful result or the caught exception.
You can chain onSuccess to handle success and onFailure to handle errors.
kotlin
val result = runCatching {
// code that might throw
}
result.onSuccess { value ->
// handle success
}.onFailure { exception ->
// handle error
}Example
This example shows how to safely parse an integer from a string using runCatching. It prints the parsed number if successful or an error message if parsing fails.
kotlin
fun main() {
val input = "123a"
val result = runCatching {
input.toInt()
}
result.onSuccess { number ->
println("Parsed number: $number")
}.onFailure { error ->
println("Failed to parse number: ${error.message}")
}
}Output
Failed to parse number: For input string: "123a"
Common Pitfalls
One common mistake is to ignore the Result and not handle failure cases, which defeats the purpose of using runCatching. Another is to use getOrNull() without checking for null, which can cause null pointer issues.
Always handle both success and failure explicitly.
kotlin
fun main() {
val input = "abc"
// Wrong: ignoring failure
val number = runCatching { input.toInt() }.getOrNull()
println("Number: $number") // prints: Number: null without error info
// Right: handle failure
runCatching {
input.toInt()
}.onSuccess {
println("Number: $it")
}.onFailure {
println("Error: ${it.message}")
}
}Output
Number: null
Error: For input string: "abc"
Quick Reference
| Function | Description |
|---|---|
| runCatching { block } | Runs code and catches exceptions, returns Result |
| onSuccess { value -> } | Handles successful result |
| onFailure { exception -> } | Handles caught exception |
| getOrNull() | Returns result or null if failure |
| getOrElse { default } | Returns result or default if failure |
Key Takeaways
Use runCatching to execute code that might throw and get a Result object.
Handle success with onSuccess and errors with onFailure for clean code.
Avoid ignoring failures; always handle exceptions explicitly.
Use getOrNull or getOrElse carefully to avoid null issues.
runCatching helps replace try-catch with more readable functional style.