1、如果不关心异常
val string = "adc"
runCatching {
Log.e(TAG, "onCreate: ${string.toInt()}")
}.getOrNull()
val string = "adc"
runCatching {
Log.e(TAG, "onCreate: ${string.toInt()}")
}
这个时候,代码有异常,日志是不会打印的,
2、捕获异常并抛出异常日志
val string = "adc"
runCatching {
Log.e(TAG, "onCreate: ${string.toInt()}")
}.getOrElse {
it.printStackTrace()
}
val string = "adc"
runCatching {
Log.e(TAG, "onCreate: ${string.toInt()}")
}.onFailure {
it.printStackTrace()
}
3、需要finally的,getOrDefault是有异常时,自定义异常信息
val string = "adc"
runCatching {
Log.e(TAG, "onCreate: ${string.toInt()}")
}.onFailure {
it.printStackTrace()
}.getOrNull().run {
Log.e(TAG, "onCreate: $this")
}
val string = "adc"
runCatching {
Log.e(TAG, "onCreate: ${string.toInt()}")
}.onFailure {
it.printStackTrace()
}.getOrDefault("ddd").run {
Log.e(TAG, "onCreate: $this")
}
4、失败直接抛出异常(崩溃)
val string = "adc"
runCatching {
Log.e(TAG, "onCreate: ${string.toInt()}")
}.getOrThrow()
|