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.
get() will throw ExecutionException if provided callable threw exception in the past (the exception is stored in the Future ). Exception thrown when attempting to retrieve the result of a task that aborted by throwing an exception. This exception can be inspected using the Throwable. getCause() method.
Callable is an Java (5) interface that can be run in a separate thread of execution and is capable of returning a value as well as throwing an exception.
Callable was added when you can add individual tasks to an Executor where you can capture the result in a Future and any exception thrown. Callable now allows you to return a value and optional declare a checked exception.
The caller has to handle the exception using a try-catch block or propagate the exception. We can throw either checked or unchecked exceptions. The throws keyword allows the compiler to help you write code that handles this type of error, but it does not prevent the abnormal termination of the program.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With