Kotlin协程吞下异常 [英] Kotlin coroutine swallows exception
问题描述
我对异常处理如何与协程一起使用感到非常困惑.
I'm very confused about how Exception handling works with coroutines.
我希望可以有一系列的挂起函数,它们之间可以像同步代码一样在它们之间传递异常.因此,如果说Retrofit抛出了IOException,我可以在挂起函数链的开头(例如在演示者中)处理该异常,以向用户显示错误.
I was hoping that it would be possible to have a chain of suspend functions that would pass Exceptions between themselves like synchronous code. So if say Retrofit threw an IOException, I could handle that exception at the beginning of the chain of suspend functions such as in a presenter to show an error to a user.
我给出了一个简单的示例来试用协同程序,但是如果我取消注释throw Exception
,则在Exception无法运行但异常不会使应用程序崩溃后调用该代码.
I made this simple example to try out coroutines but if I uncomment either throw Exception
call the code after the Exception fails to run but the Exception does not crash the app.
package com.example.myapplication
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Button
import android.widget.TextView
import kotlinx.coroutines.experimental.delay
import kotlinx.coroutines.experimental.launch
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val text = findViewById<TextView>(R.id.thing_text)
val button = findViewById<Button>(R.id.thing_button)
var count = 0
button.setOnClickListener {
launch {
count++
// throw Exception("Boom")
val string = delayedStringOfInt(count)
runOnUiThread { text.text = string }
}
}
}
suspend fun delayedStringOfInt(int: Int): String {
delay(1000)
// throw Exception("Boom")
return int.toString()
}
}
我尝试使用async
和CoroutineExceptionHandler
.
推荐答案
使用async
时,应将结果await
放在某个地方,以免丢失任何异常.
When using async
, you should await
the result somewhere so you don't lose any exceptions.
这篇关于Kotlin协程吞下异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!