【发布时间】: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