-
如果使用了 Kotlin 协程,那么会通过 ServiceLoader 的方式指定一个异常处理器 AndroidExceptionPreHandler
AndroidExceptionPreHandler
-
以 launch 启动一个协程并抛出异常为例,会经历如下流程:
-
a. 这里以 StandaloneCoroutine 为例,会走到 handleJobException 方法
handleJobException
-
b. 接着会走到 handleCoroutineException 方法,默认情况下 context 上是没有指定 CoroutineExceptionHandler 的
handleCoroutineException
-
c. 接着到 handleCoroutineExceptionImpl 方法,这里的 handlers 就是通过 ServiceLoader 获取到的,其中 currentThread 的 uncaughtExceptionHandler 为 ThreadGroup 的实例
handleCoroutineExceptionImpl
-
d. 然后到 ThreadGroup 的 uncaughtException 方法,这里会通过 Thread.getDefaultUncaughtExceptionHandler() 方法获取 DefaultUncaughtExceptionHandler 实例,结果表明为 JavaExceptionReporter 的实例,其成员变量 a 为 RuntimeInit$KillApplicationHandler 实例
ThreadGroup#uncaughtException
-
e. 最后会到 RuntimeInit$KillApplicationHandler 的 uncaughtException 方法,最终在 finally 中结束了进程。
KillApplicationHandler#uncaughtException
-
如果没有使用 kotlin 协程,会直接到 ThreadGroup 的 uncaughtException 方法
-
其中 AndroidExceptionPreHandler 中只是负责了打印日志而已
_preHandler 实例
-
RuntimeInit$LoggingHandler
LoggingHandler
网友评论