網站首頁 編程語言 正文
單個異常捕捉
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)
}
}
}
點擊按鈕后程序會閃退
但是
異常可以拿到。這就很好了
原文鏈接:https://blog.csdn.net/mp624183768/article/details/126458290
相關推薦
- 2022-11-26 使用HttpClient增刪改查ASP.NET?Web?API服務_實用技巧
- 2022-03-27 .NET?Core?使用委托實現動態流程組裝的思路詳解_實用技巧
- 2022-06-10 FreeRTOS實時操作系統隊列基礎_操作系統
- 2022-03-28 c語言經典習題之逆序字符串詳解_C 語言
- 2022-08-10 WPF中圖像處理的方法介紹_C#教程
- 2022-06-15 go語言數組及結構體繼承和初始化示例解析_Golang
- 2022-05-31 openCV實現圖像融合的示例代碼_python
- 2023-01-30 Android實現RecyclerView嵌套流式布局的詳細過程_Android
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支