2021-02-04 17:10:28.112 22307-22307/com.ted.nocrash D/timeStatistics: tryCrash:289
通过日志可以非常明显的得出两个结论
-
- 无异常时,有try与无try影响不大,都是0毫秒。
-
- 有异常时候性能下降了289 倍
当然,以上测试为极端情况,目的是放大问题,直面问题,所以以后try catch要尽可能的缩小作用域。
异常日志要怎么收集呢?
这个问题在本文开头已经给出了答案,可以通过继承Thread.UncaughtExceptionHandler并重写uncaughtException()实现日志收集。 注意:需要在Application调用初始化
class MyCrashHandler : Thread.UncaughtExceptionHandler {
override fun uncaughtException(t: Thread, e: Throwable) {
Log.e(“e”, “Exception:” + e.message);
}
fun init() {
Thread.setDefaultUncaughtExceptionHandler(this)
}
}
此时可以在uncaughtException()方法中做日志收集和上传工作。
为什么出现异常了,程序会停止运行呢?
这个问题需要了解下Android 的异常处理机制,在我们未设置Thread.UncaughtExceptionHandler之前,系统会默认设置一个,具体我们参考下ZygoteInit.zygoteInit()
public static final Runnable zygoteInit(int targetSdkVersion, long[] disabledCompatChanges,
String[] argv, ClassLoader classLoader) {
if (RuntimeInit.DEBUG) {
Slog.d(RuntimeInit.TAG, “RuntimeInit: Starting application from zygote”);
}
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, “ZygoteInit”);
RuntimeInit.redirectLogStreams();
RuntimeInit.commonIni