Kotlin异常处理runCatching,getOrNull,onFailure,onSuccess(1)
fun main(args: Array<String>) {var s1 = runCatching {1 / 1}.getOrNull()println(s1) //s1=1,打印1println("-")var s2 = runCatching {1 / 0 //发生异常}.getOrNull()println(s2) //s2为nullprintln("--")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