为什么我能';在Kotlin协同程序中是否不使用try/catch来捕获异常?

为什么我能';在Kotlin协同程序中是否不使用try/catch来捕获异常?,kotlin,asynchronous,try-catch,Kotlin,Asynchronous,Try Catch,我在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

我在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}")
        }
    }
}
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}")
    }
}
scope.launch{
Log.d(标签“测试:启动”)
试一试{
val响应:延迟=异步(SupervisorJob()){
Log.d(标记“测试:在异步块中”)
抛出IllegalStateException(“IllegalStateException”)
}
response.wait()
}捕获(e:例外){
Log.d(标记“test:error${e.message}”)
}
}

它在这里工作:请添加堆栈跟踪,以便人们可以更好地帮助您。:)我用的是MainScope,它已经有监工的工作了。public fun MainScope():CoroutineScope=ContextScope(SupervisorJob()+Dispatchers.Main)它不是那样工作的。您应该使用
SupervisorJob
进行嵌套协同例程。请看我的密码。