Rahul Singh Rahul Singh - 24 days ago 7
Java Question

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();


}
}


I have a code that resembles something like this my code task has internal method call in object call that throws sql exception but i can never catch it in the Executor service also just above the submit call i have a progressbar of javafx but that also seems to get stuck like the main ui hangs when using future . without future the progress bar works.

Answer

Future.get is a blocking call. This is why the UI hangs.

Do not use the Future to get the result. Instead use the Task's onSucceeded event handler. The onFailed event handler can be used to get the exception. Example:

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);

BTW: Both handlers run on the JavaFX application thread and can therefore safely be used to modify the UI to show the result/error to the user.

Comments