欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Kotlin全局捕捉協(xié)程異常方法詳解

 更新時(shí)間:2022年08月27日 08:34:52   作者:安果移不動(dòng)  
協(xié)程是互相協(xié)作的程序,協(xié)程是結(jié)構(gòu)化的。如果把Java的異常處理機(jī)制,照搬到Kotlin協(xié)程中,一定會(huì)遇到很多的坑。Kotlin協(xié)程中的異常主要分兩大類,協(xié)程取消異常(CancellationException) 其他異常

單個(gè)異常捕捉

  val handler = CoroutineExceptionHandler { coroutineContext, throwable ->
            Log.d(TAG, "onCreate: handler${throwable}")
        }
        Log.d(TAG, "onCreate:1")
        findViewById<Button>(R.id.button).also {
            it.setOnClickListener {
                GlobalScope.launch(handler) {
                    Log.d(TAG, "onCreate: onClick")
                    "anc".substring(10)
                }
            }
        }

launch里面如果不寫handler

可以使用這樣的方式來創(chuàng)建全局異常捕獲處理

在main目錄下

新建 resources\META-INF\services\kotlinx.coroutines.CoroutineExceptionHandler

注意沒有后綴哦

然后回到j(luò)ava類里面 隨便找個(gè)位置創(chuàng)建class類

內(nèi)容

package com.example.coroutine
import android.util.Log
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlin.coroutines.CoroutineContext
class GlobalCoroutineExceptionHandler : CoroutineExceptionHandler {
    override val key = CoroutineExceptionHandler
    private  val TAG = "GlobalCortineExceptionH"
    override fun handleException(context: CoroutineContext, exception: Throwable) {
        Log.d(TAG, "handleException:${exception} ")
    }
}

根據(jù)包名和類目

package com.example.coroutine.

GlobalCoroutineExceptionHandler

我們可以確定這個(gè)文件的路徑為

com.example.coroutine.GlobalCoroutineExceptionHandler

寫到剛才創(chuàng)建的沒有后綴的文件當(dāng)中去

程序里刪除 hander

      findViewById<Button>(R.id.button).also {
            it.setOnClickListener {
                GlobalScope.launch {
                    Log.d(TAG, "onCreate: onClick")
                    "anc".substring(10)
                }
            }
        }

點(diǎn)擊按鈕后程序會(huì)閃退

但是

異??梢阅玫?。這就很好了

到此這篇關(guān)于Kotlin全局捕捉協(xié)程異常方法詳解的文章就介紹到這了,更多相關(guān)Kotlin協(xié)程異常內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論