[英]Try/catch in Android Kotlin coroutine leads to a crash
In my android kotlin project, I want to run the following code:在我的 android kotlin 项目中,我想运行以下代码:
CoroutineScope(Dispatchers.IO).launch {
try
{
doStuff()
}
catch (exception: Exception)
{
exception.printStackTrace()
}
}
For some reason, it looks like it works well if I compile and run that code using Android Studio 3.6.3, but not anymore with Android Studio 4, as I get the following error:出于某种原因,如果我使用 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)
I figured out that when I remove the try/catch, like the following:我发现当我删除 try/catch 时,如下所示:
CoroutineScope(Dispatchers.IO).launch {
doStuff()
}
it works.有用。
How can I use the try/catch
in my coroutine again?如何再次在协程中使用
try/catch
?
Thanks.谢谢。
Let me explain on this Coroutine have two methods- Async and launch.让我解释一下这个协程有两种方法——异步和启动。 Launch doesn't return anything but Asynk return value.
Launch 不返回任何内容,只返回 Asynk 返回值。
If you need to use a try-catch in Coroutine Launch.如果您需要在 Coroutine Launch 中使用 try-catch。 Just modify you code and add async.
只需修改您的代码并添加异步。 However, by adding Asynk it will properly return the exception in your code.
但是,通过添加 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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.