【问题标题】:Why exception thrown from child custom scope is not caught by parent catch block in Kotlin coroutine?为什么从子自定义范围抛出的异常没有被 Kotlin 协程中的父 catch 块捕获?
【发布时间】: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


    【解决方案1】:

    在您的第一个示例中,确实没有父子关系。 parentScopechildScope 都是单独创建的,它们彼此独立运行。仅仅因为您将一个代码块放在另一个代码块中并不意味着它们有任何关联。

    withContext()则不同,它使用当前作用域(parentScope)来执行代码。

    换句话说:无论何时你使用someScope.launch(),这就像明确要求切换到完全不同的执行上下文。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-07
      • 2012-02-24
      • 2019-04-06
      • 2014-08-16
      • 2019-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多