try {
lifecycleScope.launch {
launch {
delay(3000)
throw Exception()
}
}
} catch (e: Exception) {
}
try catch 能捕获到的仅仅是 try 模块内执行的同步方法的异常,而Java中协程的本质是多线程框架。launch内相当于异步代码。try catch执行之前的异常 以及 try catch 内的异步方法所产生的异常,都是不会被捕获的。
和Handler().post类似
try {
Handler().post {
throw Exception()
}
thread {
}.start()
}catch (e:Exception){
}
官方推荐异常处理
https://www.kotlincn.net/docs/reference/coroutines/exception-handling.html