如何在 java fx 应用程序中捕获任务异常?

How to catch the task exception in java fx application?

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import javafx.concurrent.Task;


public class T {

    public static void main(String[] args) {

        ExecutorService executorService = Executors.newSingleThreadExecutor();

        Task t = new Task(){

            @Override
            protected Object call() throws Exception {
                System.out.println(1/0);
                return null;
            }

        };

        //My progresss Bar in JavaFX
        //Progressbar.progressProperty().bind(t.progressProperty());

        Future future = executorService.submit(t);

        try {
            future.get();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  //returns null if the task has finished correctly.

        executorService.shutdown();


}
}

我有一个类似于这样的代码我的代码任务在对象调用中有内部方法调用抛出 sql 异常但我永远无法在 Executor 服务中捕获它也在我的提交调用之上javafx 的进度条,但它似乎也像使用 future 时主 ui 挂起一样卡住了。没有未来进度条工作。

Future.get 是阻塞调用。这就是 UI 挂起的原因。

不要使用Future得到结果。而是使用 TaskonSucceeded 事件处理程序。 onFailed 事件处理程序可用于获取异常。示例:

t.setOnSucceeded(evt -> System.out.println(t.getValue()));
t.setOnFailed(evt -> {
    System.err.println("The task failed with the following exception:");
    t.getException().printStackTrace(System.err);
});
executorService.submit(t);

顺便说一句:JavaFX 应用程序线程上的两个处理程序 运行 因此可以安全地用于修改 UI 以向用户显示 result/error。