Kotlin协程吞下异常

TTr*_*mit 5 android exception kotlin kotlinx.coroutines

我对异常处理如何与协程一起使用感到非常困惑。

我希望有可能拥有一系列挂起函数,这些函数可以像同步代码一样在它们之间传递异常。因此,如果说Retrofit抛出了IOException,我可以在挂起函数链的开头(例如在演示者中)处理该异常,以向用户显示错误。

我给出了一个简单的示例来试用协程,但是如果我取消注释,throw Exception则在异常无法运行后调用该代码,但异常不会使应用程序崩溃。

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()
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用asyncCoroutineExceptionHandler

Ale*_*nov 2

使用时async,您应该将await结果放在某个地方,这样就不会丢失任何异常。