如何重新抛出异常 [英] How to re-throw an exception
问题描述
在我的onCreate()中,我设置了一个UncaughtException处理程序,如下所示:
In my onCreate() I set an UncaughtException handler as follows:
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());
}
});
它工作正常,但我想恢复系统显示强制关闭的默认行为给用户的对话框。
It works OK, but I would like to get back the system's default behavior of displaying the force-close dialog to the user.
如果我尝试用 KillProcess()
调用> throw throwable 编译器抱怨我需要用try / catch包围它。
If I try to replace the KillProcess()
call with a throw throwable
the compiler complains that I need to surround it with a try/catch.
如果我用try / catch包围它:
If I surround it with a 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包围。
The compiler still complains that throw throwable
needs to be surrounded with a try/catch.
如何重新抛出那个throwable?这样,除了信息性 Log.e()
之外,系统的行为与以前完全一样:因为我从未设置默认的UncaughtException处理程序。
How do I re-throw that throwable? Such that except for that informative Log.e()
the system behaves exactly as before: As is I never set a default UncaughtException handler.
推荐答案
尝试:
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());
改编自这个答案。
这篇关于如何重新抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!