2

I'm using an ExecutorService to run tests upon a system. The problem arises when a test fails for some reason. These reason can be a many, and of course I'm logging these errors.

But I would like to, in real-time, notify the user of an error. So when an error occurs, the longer it reaches the top, it becomes a TestFailedException with a message and a cause. I would like to catch this exception and notify the user, but I can't seem to do that.

This is an example of a method that is actually starting the thread that runs the test:

public void asyncRunTestfixture(Concretetest concretetest) {

    ExecutorService executor = Executors.newCachedThreadPool();
    FutureTask<Boolean> futureTask_1 = new FutureTask<Boolean>(new Callable<Boolean>() {
        @Override
        public Boolean call() throws TestFailedException {
            return RunTestInFixture(concretetest);          
        }

      });
      executor.execute(futureTask_1);
      executor.shutdown(); 
}

But even though call throws an exception, I can't catch it elsewhere, neither now or if I say the asyncRunTestfixture methods throws an exception.

How can I solve this?

Solomon Slow
  • 25,130
  • 5
  • 37
  • 57
Benjamin Larsen
  • 345
  • 2
  • 15
  • 1
    The exception will be thrown to you when you call `futureTask_1.get()` to get the result. It will be wrapped inside an `ExecutionException`. – Erwin Bolwidt May 23 '16 at 06:08
  • Refer this answer from another [post](http://stackoverflow.com/questions/12305667/how-is-exception-handling-done-in-a-callable) – Akhil May 23 '16 at 06:09
  • @ErwinBolwidt, the exception is thrown when it is thrown. The exception is _caught_ by the pool worker thread, and the handler stores a refernce to the exception object in the `Future`. Finally, the `ExecutionException` is thrown when the client calls the future's `get()` method. – Solomon Slow May 23 '16 at 13:35

1 Answers1

4

Calling get() on the completed futureTask_1 will throw an ExecutionException typically wrapping the cause when the task threw some exception.

Thomas B Preusser
  • 1,159
  • 5
  • 10