怎么用Kotlin全局捕捉协程异常
更新:HHH   时间:2023-1-7


本篇内容介绍了“怎么用Kotlin全局捕捉协程异常”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

单个异常捕捉

  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

可以使用这样的方式来创建全局异常捕获处理

在main目录下

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

注意没有后缀哦

然后回到java类里面 随便找个位置创建class类

内容

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} ")
    }
}

根据包名和类目

package com.example.coroutine.

GlobalCoroutineExceptionHandler

我们可以确定这个文件的路径为

com.example.coroutine.GlobalCoroutineExceptionHandler

写到刚才创建的没有后缀的文件当中去

程序里删除 hander

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

点击按钮后程序会闪退

但是

异常可以拿到。这就很好了

“怎么用Kotlin全局捕捉协程异常”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注天达云网站,小编将为大家输出更多高质量的实用文章!

返回开发技术教程...