kotlin: supervisorScope和coroutineScope直接子协程的区别
一,区别:
supervisorScope 的直接子协程是可以捕获到异常的,因为这些 supervisorScope 的子协程需要自己处理异常。
与 supervisorScope 不同的是,coroutineScope 的直接子协程不能捕捉到异常
二,例子:supervisorScope的直接子协程可以捕获到异常
代码:
//处理按钮点击事件
binding.button3.setOnClickListener {
runBlocking {
val handler = CoroutineExceptionHandler { _, e ->
println("捕捉到了异常: $e")
}
supervisorScope {
launch(handler) {
println("将要抛出异常")
throw Exception("发生了异常")
}
}
}
}
运行结果:
三,例子:coroutineScope 的直接子协程不能捕捉到异常
代码:
//处理按钮点击事件
binding.button2.setOnClickListener {
runBlocking {
val handler = CoroutineExceptionHandler { _, e ->
println("捕捉到了异常: $e")
}
coroutineScope {
launch(handler) {
println("将要抛出异常")
throw Exception("发生了异常")
}
}
}
}
运行结果: