【问题标题】:Try/catch in Android Kotlin coroutine leads to a crashAndroid Kotlin 协程中的 Try/catch 导致崩溃
【发布时间】:2020-06-14 15:31:34
【问题描述】:

在我的 android kotlin 项目中,我想运行以下代码:

CoroutineScope(Dispatchers.IO).launch {
   try
   {
      doStuff()
   }
   catch (exception: Exception)
   {
      exception.printStackTrace()
   }
}

出于某种原因,如果我使用 Android Studio 3.6.3 编译和运行该代码,它看起来运行良好,但在 Android Studio 4 中不再适用,因为我收到以下错误:

java.lang.VerifyError: Verifier rejected class com.myproject.DemoInteractor$connect$1: java.lang.Object com.myproject.DemoInteractor$connect$1.invokeSuspend(java.lang.Object) failed to verify: java.lang.Object com.myproject.DemoInteractor$connect$1.invokeSuspend(java.lang.Object): [0x95] register v3 has type Reference: java.lang.Throwable but expected Precise Reference: kotlin.jvm.internal.Ref$ObjectRef (declaration of 'com.myproject.DemoInteractor$connect$1' appears in /data/app/com.wezeejay.wezeejay-DjGgFSKkc9RkPSXWhfTUfQ==/base.apk:classes2.dex)

我发现当我删除 try/catch 时,如下所示:

CoroutineScope(Dispatchers.IO).launch {
   doStuff()
}

它有效。

如何在我的协程中再次使用try/catch

谢谢。

【问题讨论】:

    标签: android kotlin kotlin-coroutines


    【解决方案1】:

    让我解释一下这个协程有两种方法——异步和启动。 Launch 只返回 Asynk 返回值。

    如果你需要在 Coroutine Launch 中使用 try-catch。 只需修改您的代码并添加异步。但是,通过添加 Asynk,它会在您的代码中正确返回异常。

    CoroutineScope(Dispatchers.IO).launch {
         try {
                val deferred = async {
                    codeThatCanThrowExceptions()
                }
                deferred.await()
            } catch(e: Exception) {
                // Exception thrown in async WILL NOT be caught here 
                // but propagated up to the scope
            }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-01
      • 2021-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多