gpt4 book ai didi

kotlin - 为什么我不能使用try/catch来捕获Kotlin协程中的异常?

转载 作者:行者123 更新时间:2023-12-02 12:55:15 28 4
gpt4 key购买 nike

我在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)

最佳答案

除非您使用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 Documentationinfomore info

关于kotlin - 为什么我不能使用try/catch来捕获Kotlin协程中的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63930492/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com