18

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 method and is the bottommost method of the thread stack.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
user1649415
  • 1,085
  • 4
  • 12
  • 24
  • I'm not sure about what's your question. Is it about the implementation of classes rethrowing an exception throwed by a Callable ? – Denys Séguret Sep 06 '12 at 18:02
  • No. My simple doubt is that when callable throws an exception who catches it. And if an exception in call method of Callable can be thrown then why not run of Runnable throw an exception – user1649415 Sep 06 '12 at 18:06
  • Runnable is run in a separate thread (hence the name). Callable isn't (hence the name). In fact, you CAN throw an exception out of a Runnable, but there's nothing to handle it (other than the JVM's "shoot me" handler). – Hot Licks Sep 06 '12 at 18:14

2 Answers2

18

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
}
ErikE
  • 48,881
  • 23
  • 151
  • 196
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
6

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)

main--
  • 3,873
  • 1
  • 16
  • 37
  • May I know which method catches callable exception coz as per my understanding,callable is called when a thread is started and call is the first method to occupy the call stack.Please correct me if I am wrong. – user1649415 Sep 06 '12 at 18:38
  • @user1649415 As I am saying in my answer `Callable.call()` **can't** be the first method to occupy the call stack. It's always called somewhere else and if it throws an exception that exception is usually caught and later rethrown if you try to get the `Future`'s value. – main-- Sep 06 '12 at 18:48