kotlin: 使用 CoroutineExceptionHandler 处理复杂结构的协程异常
一,例一,用 CoroutineExceptionHandler处理协程异常
代码:
//处理按钮点击事件
binding.button1.setOnClickListener {
runBlocking {
//定义异常处理handler
val myExceptionHandler = CoroutineExceptionHandler { _, throwable ->
println("Catch exception: $throwable")
}
// 注意这里
val scope = CoroutineScope(coroutineContext + Job() + myExceptionHandler)
scope.launch {
async {
delay(100L)
}
launch {
delay(100L)
launch {
delay(100L)
1 / 0 // 故意制造异常
}
}
delay(100L)
}
delay(1000L)
println("End")
}
}
运行结果:
二,CoroutineExceptionHandler不起作用的情况
CoroutineExceptionHandler 只在顶层的协程当中才会起作用。
也就是说,当子协程当中出现异常以后,它们都会统一上报给顶层的父协程,
然后顶层的父协程才会去调用 CoroutineExceptionHandler,来处理对应的异常。
协程的一条准则:
使用 CoroutineExceptionHandler 处理复杂结构的协程异常时,它仅在顶层协程中起作用。