??? Handling Errors in Kotlin with runCatching

??? Handling Errors in Kotlin with runCatching

This is the Kotlin way of error handling where the runCatching context returns a Result class, similar to that in Rust, represents either the success or failure of an operation.

Let’s go back to our initial example.

@Throws
fun Calculate() {
    throw ArithmeticException()
}

fun main() {
    try {
        Calculate()
    } catch(e: Exception) {
        println("ErrorCaught: $e")
    }
}        
Re-write it in the Kotlin way, we have
fun main() {
    runCatching {
        Calculate()
    }.onFailure {
        println("ErrorCaught: $it")
    }
}        
Note that instead of explicitly specifying Exception e, we can simply use it to point to it.

And if we want to use the explicit Result,

fun main() {
    val result = runCatching {
        Calculate()
    }
    result.onFailure {
        println("ErrorCaught: $it")
    }
}        
Just like the Result in Rust, we can also use it as a return type of the function. Instead of throwing or return, we can use Result.scucess or Result.failure. We will then use Fold to obtain the result for both the success and the failure.
fun Calculate(number: Int):Result<Int> {
  return if (number == 0) {
        Result.failure(ArithmeticException())
    } else {
        Result.success(number)
    }
}


fun main() {
    val number = Calculate(0)
    number.fold(
        onSuccess = {
            println(number)
        },
        onFailure = {
            println("ErrorCaught: $it")
        }
    )
}        


要查看或添加评论,请登录

Rehan Ali的更多文章

  • Why StateFlow?

    Why StateFlow?

    StateFlow is a new observable data holder class in Android that was introduced in Kotlin 1.3.

  • Why should I secure my API-Keys?

    Why should I secure my API-Keys?

    Api-Keys are considered secret values that only the developer should know of. They are keys to accessing our servers…

  • The Nothing type

    The Nothing type

    is an expression in Kotlin, so you can use it, for example, as part of an Elvis expression: The expression has the type…

  • Kotlin annotation processor

    Kotlin annotation processor

    Why Kotlin annotation processor is called Kapt? Here’s the interesting story.→ Back in the days, when Kotlin was pretty…

  • Unit-returning functions

    Unit-returning functions

    If a function does not return a useful value, its return type is . is a type with only one value - .

  • ExtensionFunctionKt

    ExtensionFunctionKt

    Kotlin provides the ability to extend a class or an interface with new functionality without having to inherit from the…

  • Inline functions

    Inline functions

    Using higher-order functions imposes certain runtime penalties: each function is an object, and it captures a closure…

社区洞察