从java任务抛出异常不起作用

时间:2018-01-22 16:33:16

标签: java exception task

我试图在一个单独的线程上运行的任务中抛出一个异常。然后我想在调用线程上捕获异常。请参阅下面的我的试用版:
当我现在运行代码时,它挂起在"行抛出新的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");
        }
    };
}

1 个答案:

答案 0 :(得分:0)

试试这个.... 行抛出异常应该在try块里面

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