小例子:
public class App {
public static void main(String[] args) {
throw new RuntimeException("Test exception");
}
}按预期印刷如下:
Exception in thread "main" java.lang.RuntimeException: Test exception
at App.main(App.java:5)让我们修改这个程序:
public class App {
public static void main(String[] args) {
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
if (e instanceof RuntimeException) throw (RuntimeException)e;
}
});
throw new RuntimeException("Test exception");
}
}指纹:
Exception: java.lang.RuntimeException thrown from the UncaughtExceptionHandler in thread "main"问题:
为什么消息不包含发生在哪里的任何信息,并且没有堆栈跟踪,消息?
对我来说,异常消息看起来很奇怪。
发布于 2013-09-20 08:53:42
Java文档说:
void uncaughtException(Thread t, Throwable e)方法,当给定线程由于给定的未命名异常而终止时,将调用。Java虚拟机将忽略此方法引发的任何异常。
因此,如果您希望程序终止某些异常并打印它们的消息/堆栈跟踪,那么您应该这样做:
@Override
public void uncaughtException(Thread t, Throwable e) {
if (e instanceof RuntimeException) {
e.printStackTrace();
System.exit(1);
}
}https://stackoverflow.com/questions/18912439
复制相似问题