在我的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
?
谢谢。
答案 0 :(得分:0)
让我解释一下此协程有两种方法-异步和启动。 启动只返回Asynk返回值。
如果您需要在协同程序启动中使用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
}
}