How is exception handling done in a Callable

前端 未结 2 953
长发绾君心
长发绾君心 2020-12-31 04:24

I understand that callable\'s call can throw the exception to the parent method calling it which is not the case with runnable.

I wonder how because it\'s a thread m

相关标签:
2条回答
  • 2020-12-31 04:32

    Callable.call() can't be the bottommost stack frame. It's always called by another method that will then catch the exception. Callable should usually be used to asynchronously compute values and later get them with a Future object. The operation might throw an exception that is later rethrown when you try to get the Future's value.

    Runnable is simply supposed to run an operation that doesn't return anything. All exception handling should be done within the Runnable because it's unclear how any exceptions thrown in Runnable.run() should be handled. (The exception from a Callable is usually returned to the caller with the Future)

    0 讨论(0)
  • 2020-12-31 04:56

    The point of Callable is to have your exception thrown to your calling thread, for example when you get the result of a Future to which you submitted your callable.

    public class CallableClass implements Callable<String> {
    ...
    }
    
    ExecutorService executor = new ScheduledThreadPoolExecutor(5);
    Future<Integer> future = executor.submit(callable);
    
    try {
        System.out.println(future.get());
    } catch (Exception e) {
        // do something
    }
    
    0 讨论(0)
提交回复
热议问题