Mark Vrijlandt
Mark Vrijlandt

Reputation: 11

throw exception from java task does not work

I am trying to throw an exception inside a task which is run on a separate thread. Then I want to catch the exception on the calling thread. See my trial below:
When I run the code now it hangs at the line with "throws new RuntimeException.."

Task calcTask = createCalcTask();

ExecutorService executor = Executors.newFixedThreadPool(1);
Future future = executor.submit(calcTask);
try {
    future.get();
} catch (ExecutionException ex) {
    ex.getCause().printStackTrace();
} catch (InterruptedException e1) {
    e1.printStackTrace();
}

public Task<Object> createCalcTask() {
    return new Task<Object>() {
        @Override
        protected Object call() throws Exception {              
            throw new RuntimeException("testE");
        }
    };
}

Upvotes: 1

Views: 106

Answers (1)

Jagruti
Jagruti

Reputation: 43

try this.... line throwing exception should be inside try block

try {
   Future future = executor.submit(calcTask); //
   future.get();
} catch (ExecutionException ex) {
   ex.printStackTrace();
}

Upvotes: 0

Related Questions