??? 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")
        }
    )
}        


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

社区洞察

其他会员也浏览了