Kotlin异常处理runCatching,getOrNull,onFailure,onSuccess(1)
fun main(args: Array<String>) {
var s1 = runCatching {
1 / 1
}.getOrNull()
println(s1) //s1=1,打印1
println("-")
var s2 = runCatching {
1 / 0 //发生异常
}.getOrNull()
println(s2) //s2为null
println("--")
runCatching {
1 / 1
}.onFailure {
println("onFailure $it") //不会执行,因为runCatching没有失败
}.onSuccess {
println("onSuccess $it") //执行,因为runCatching成功
}
println("---")
runCatching {
1 / 0 //发生异常
}.onFailure {
println("onFailure $it") //执行,因为runCatching失敗了
}.onSuccess {
println("onSuccess $it") //不会执行,因为runCatching沒有成功
}
}
1
null
onSuccess 1
onFailure java.lang.ArithmeticException: / by zero
kotlin异常处理try-catch-finally_zhangphil的博客-CSDN博客b-catch: java.lang.RuntimeException: b发生异常。kotlin异常处理try-catch-finally。https://blog.csdn.net/zhangphil/article/details/129800172
版权归原作者 zhangphil 所有, 如有侵权,请联系我们删除。