網站首頁 編程語言 正文
單個異常捕捉
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-12-04 Golang如何快速構建一個CLI小工具詳解_Golang
- 2022-09-26 Redis刪除策略的三種方法及逐出算法_Redis
- 2022-09-23 Golang分布式應用定時任務示例詳解_Golang
- 2023-12-12 線程并發協作(生產者/消費者模式)
- 2022-05-14 shell腳本如何讀取properties文件中的值_linux shell
- 2022-04-02 Python字符串與正則表達式詳細介紹_python
- 2022-04-18 WPF框架Prism中對話框Dialog用法介紹_自學過程
- 2023-03-03 PostgreSQL死鎖了怎么辦及處理方法_PostgreSQL
- 最近更新
-
- 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同步修改后的遠程分支