【问题标题】:throw exception from java task does not work从java任务抛出异常不起作用
【发布时间】:2018-01-22 16:33:15
【问题描述】:

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

【问题讨论】:

  • 您的线程无法处理 generic RuntimeException...

标签: java exception task


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2017-01-01
    • 2019-09-29
    相关资源
    最近更新 更多