Rahul Singh Rahul Singh - 6 months ago 42
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(){

protected Object call() throws Exception {
return null;


//My progresss Bar in JavaFX

Future future = executorService.submit(t);

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



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.


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

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.