在我的onCreate()中,如下设置UncaughtException处理程序:
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable throwable) {
Log.e(getMethodName(2), "uncaughtException", throwable);
android.os.Process.killProcess(android.os.Process.myPid());
}
});
它可以正常工作,但是我想找回系统的默认行为,即向用户显示强制关闭对话框。
如果我尝试用
KillProcess()
替换throw throwable
调用,则编译器会提示我需要用try/catch包围它。如果我尝试/捕获它:
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable throwable) {
try {
Log.e(getMethodName(2), "uncaughtException", throwable);
throw throwable;
}
catch (Exception e) {
}
finally {
}
}
});
编译器仍然提示
throw throwable
需要用try/catch包围。我如何重新抛出该抛出?这样,除了提供信息丰富的
Log.e()
之外,系统的行为与之前完全相同:我从未设置默认的UncaughtException处理程序。 最佳答案
尝试:
public class CustomExceptionHandler implements UncaughtExceptionHandler {
private UncaughtExceptionHandler defaultUEH;
public CustomExceptionHandler() {
this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
}
public void uncaughtException(Thread t, Throwable e) {
Log.e("Tag", "uncaughtException", throwable);
defaultUEH.uncaughtException(t, e);
}
}
进而
Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler());
改编自this答案。