Kotlin异常处理runCatching,getOrDefault,getOrNull run(2)
fun main(args: Array<String>) {
runCatching {
1 / 0 //发生异常
}.getOrNull().run {
println(this)
}
println("-")
runCatching {
1 / 1 //正常
}.getOrNull().run {
println(this)
}
println("--")
runCatching {
1 / 0 //发生异常
}.onFailure {
it.printStackTrace()
}.getOrDefault(2023).run {
println(this)
}
}
null
-
1
--
2023
java.lang.ArithmeticException: / by zero
at MainKt.main(Main.kt:20)