考虑以下代码:
Thread.setDefaultUncaughtExceptionHandler((Thread t, Throwable e) -> {
System.out.println("An exception occurred!");
});
// set the exception handler for the JavaFX application thread
Thread.currentThread().setUncaughtExceptionHandler((Thread t, Throwable e) -> {
System.out.println("An exception occurred!");
});
Task<?> task = new Task() {
@Override
public Void call() throws Exception {
throw new RuntimeException("foobar");
};
};
new Thread(task).start();
如果我们运行代码,运行时异常不会触发默认的异常处理程序,而是被任务所消耗。我发现唯一对抗这种情况的方法是在task.setOnFailed中重新抛出异常:
task.setOnFailed((WorkerStateEvent t) -> {
throw new RuntimeException(task.getException());
});
自从JavaFX 8开始支持UncaughtExceptionHandler,为什么异常没有传播到异常处理程序?
throw task.getException();
但编译器只是报错。 - user555