runCatching异常捕获onSuccess/onFailure返回函数,Kotlin

runCatching异常捕获onSuccess/onFailure返回函数,Kotlin

 

fun test(a: Int, b: Int) {
    runCatching {
        a / b
    }.onSuccess {
        println("onSuccess: $it")
        return ok(it)
    }.onFailure {
        println("onFailure: $it")
        return fail(it)
    }
}

fun ok(o: Any) {
    println("ok: $o")
}

fun fail(o: Any) {
    println("fail: $o")
}

fun main(args: Array) {
    test(0, 1)
    test(1, 0)
}

 

onSuccess: 0
ok: 0
onFailure: java.lang.ArithmeticException: / by zero
fail: java.lang.ArithmeticException: / by zero

 

 

 

 

Kotlin异常处理runCatching,getOrNull,onFailure,onSuccess(1)-CSDN博客文章浏览阅读533次。b-catch: java.lang.RuntimeException: b发生异常。kotlin异常处理try-catch-finally。kotlin异常处理try-catch-finally_zhangphil的博客-CSDN博客。https://blog.csdn.net/zhangphil/article/details/133279853Kotlin异常处理runCatching,getOrDefault,getOrNull run(2)-CSDN博客文章浏览阅读93次。b-catch: java.lang.RuntimeException: b发生异常。kotlin异常处理try-catch-finally。kotlin异常处理try-catch-finally_zhangphil的博客-CSDN博客。b-catch: java.lang.RuntimeException: b发生异常。kotlin异常处理try-catch-finally。kotlin异常处理try-catch-finally_zhangphil的博客-CSDN博客。https://blog.csdn.net/zhangphil/article/details/133279933

 

你可能感兴趣的:(kotlin,kotlin)