【问题标题】:Why i can't use try/catch to catch exception in Kotlin coroutine?为什么我不能使用 try/catch 在 Kotlin 协程中捕获异常?
【发布时间】:2020-09-17 02:41:26
【问题描述】:

我在 Android 中有如下代码:


//use MainScope
private val scope = MainScope()

private fun test() {
    scope.launch {
        Log.d(TAG, "test: launch")
        try {
            val response: Deferred<String> = async {
                Log.d(TAG, "test: in async block")
                throw IllegalStateException("an IllegalStateException")
            }
            response.await()
        } catch (e: Exception) {
            Log.d(TAG, "test: error ${e.message}")
        }
    }
}

我使用MainScope 启动协程,并使用async 在其中启动子协程。当我使用try/catch 捕获子协程异常时,我失败了,应用程序崩溃了。谁能告诉我为什么?

崩溃信息如下:

D/AsyncExceptionTestActiv: test: launch
D/AsyncExceptionTestActiv: test: in async block
D/AsyncExceptionTestActiv: test: error an IllegalStateException
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.hm.dumingwei.kotlinandroid, PID: 18461
    java.lang.IllegalStateException: an IllegalStateException
        at com.hm.dumingwei.kotlinandroid.AsyncExceptionTestActivity$test$1$response$1.invokeSuspend(AsyncExceptionTestActivity.kt:61)
        at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
        at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:241)
        at android.os.Handler.handleCallback(Handler.java:761)
        at android.os.Handler.dispatchMessage(Handler.java:98)
        at android.os.Looper.loop(Looper.java:156)
        at android.app.ActivityThread.main(ActivityThread.java:6517)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)

【问题讨论】:

  • 在这里工作:pl.kotl.in/P34W08EZW
  • 请添加堆栈跟踪,以便人们可以更好地帮助您。 :)

标签: kotlin asynchronous try-catch


【解决方案1】:

嵌套协程中抛出的异常会传播到父协程,除非你使用SupervisorJob:

scope.launch {
    Log.d(TAG, "test: launch")
    try {
        val response: Deferred<String> = async(SupervisorJob()) {
            Log.d(TAG, "test: in async block")
            throw IllegalStateException("an IllegalStateException")
        }
        response.await()
    } catch (e: Exception) {
        Log.d(TAG, "test: error ${e.message}")
    }
}

Kotlin Documentation、info、more info

【讨论】:

  • 我使用 MainScope ,它已经有 SupervisorJob。 public fun MainScope(): CoroutineScope = ContextScope(SupervisorJob() + Dispatchers.Main)
  • 这样不行。对于嵌套协程,您应该使用 SupervisorJob。请看我的代码。
猜你喜欢
  • 2021-05-13
  • 2015-06-21
  • 2011-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-15
  • 2013-12-05
  • 1970-01-01
相关资源
最近更新 更多