【发布时间】:2023-02-09 19:00:28
【问题描述】:
val parentScope = CoroutineScope(Dispatchers.Main)
val childScope = CoroutineScope(Dispatchers.IO)
parentScope.launch {
try{
childScope.launch{
//code ....
throw CustomError("error", null)
}
} catch(cause: CustomError){
// It did not get execute when custom scope is used
}
}
在上面的代码 sn-p 中,应用程序崩溃了。这从它抛出的异常没有被捕获进入 parentScope catch 块。
但是,如果我们将自定义范围(此处为 childScope)替换为
supervisorScope or
coroutineScope or
withContext
它抓住了例外。
parentScope.launch {
try{
withContext(Dispatchers.IO){
//code
throw CustomError("error", null)
}
} catch(cause: CustomError){
// It get execute when withContext/supervisorScope
}
}
为什么从子自定义范围抛出的异常没有被父 catch 块捕获?
【问题讨论】:
标签: android exception kotlin-coroutines