类 StandardCoroutine 中的 it.uncaughtExceptionHandler.uncaughtException(it, e) 到底是什么意思?在网上也没搜到啥靠谱的答案。
为啥他会令resumeWithException 后协程抛出异常崩溃掉?
class StandardCoroutine(context: CoroutineContext) : AbstractCoroutine<Unit>(context) {
override fun handleJobException(e: Throwable): Boolean {
context[CoroutineExceptionHandler]?.handleException(context, e) ?:
Thread.currentThread().let {
it.uncaughtExceptionHandler.uncaughtException(it, e)
}
return true
}
}这是简单的测试代码
suspend fun main(){
log(1)
val job = GlobalScope.launch{
log(2)
val s: String = demo2()
log(s)
}
job.join()
log(5)
}
suspend fun demo2() = suspendCoroutine<String> { c ->
thread{
Thread.sleep(1000)
c.resumeWithException(Exception("test 500"))
}
}上面的例子中如果注释掉 it.uncaughtExceptionHandler.uncaughtException(it, e),那么就不会抛出异常。反之就抛异常。
而根据分析BaseContinuationImpl=>resumeWith函数,分析可知 resumeWithException 操作并不会导致抛异常。