考虑这段代码:
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,为什么异常不传播到异常处理程序?
在 - 的里面Task.call()
方法只是抛出异常并添加一个ChangeListener
像这样的任务:
task.exceptionProperty().addListener((observable, oldValue, newValue) -> {
if(newValue != null) {
Exception ex = (Exception) newValue;
ex.printStackTrace();
}
});
然后,在任务因异常失败后,侦听器会通知您在执行过程中抛出了哪个异常。您可以轻松更换线路ex.printStackTrace();
与Alert
如果您位于 JavaFX 执行线程中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)