Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is exception handling done in a Callable

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.

like image 902
user1649415 Avatar asked Sep 06 '12 17:09

user1649415


People also ask

How do you handle exceptions in Callable?

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.

Is Callable thread return exception and handling of exception?

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.

Can Callable throw checked 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.

How do you catch exception in call method?

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.


1 Answers

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
}
like image 94
Denys Séguret Avatar answered Sep 21 '22 08:09

Denys Séguret