软件编程
位置:首页>> 软件编程>> Android编程>> Kotlin全局捕捉协程异常方法详解

Kotlin全局捕捉协程异常方法详解

作者:安果移不动  发布时间:2022-10-09 23:27:03 

标签: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

Kotlin全局捕捉协程异常方法详解

注意没有后缀哦

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

Kotlin全局捕捉协程异常方法详解

内容

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

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

Kotlin全局捕捉协程异常方法详解

程序里删除 hander

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

点击按钮后程序会闪退

但是

Kotlin全局捕捉协程异常方法详解

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

来源:https://blog.csdn.net/mp624183768/article/details/126458290

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com