为什么在corutineAScope块中进行try / catch仍然由于捕获的异常而崩溃

时间:2019-07-15 15:17:35

标签: exception kotlin-coroutines

  fun main() = runBlocking {
        coroutineScope {

            val child = async {
                Log.e("+++", "+++  in  async{}, throw exception , ${Thread.currentThread().name}")
                throw Exception("test exception with await() in async")
            }

            try {
                child.await()
            } catch(ex: Throwable) {
                Log.e("+++", "+++  child.await() caught  exception $ex, ${Thread.currentThread().name}")
            }

        }
  }

日志"+++ child.await() caught exception java.lang.Exception: test exception with await() in aync, main"。显示已捕获到异常,但仍然使应用程序崩溃。

为什么捕获到的期望仍使协程使应用程序崩溃?

3 个答案:

答案 0 :(得分:1)

根据coroutineScope的文档:

  

此功能旨在并行分解工作。当此作用域中的任何子协程失败时,该作用域将失败,并且所有其他子级都将被取消(有关其他行为,请参见supervisorScope)。该函数在给定的块及其所有子协程完成后立即返回。

删除coroutineScope,它应该可以正常工作。

答案 1 :(得分:0)

find this is helpful as wellhere

whenever a coroutine created by async() throws an exception, 
the same exception is thrown both by its Deferred.await() 
and inside the body of the parent coroutine as well! 
This means that, no matter if we catch the exception by surrounding await() with try/catch, 
our app is still going to crash because the exception is not thrown just 
from the await() suspension point

答案 2 :(得分:0)

子协程抛出的异常会一直上升到其直接父级。您必须尝试在父协程中捕获异常。这样应用程序就不会崩溃。

相关问题