I\'m converting my code from using Handler to AsyncTask. The latter is great at what it does - asynchronous updates and handling of results in the
Actually, AsyncTask use FutureTask & Executor, FutureTask support exception-chain First let's define a helper class
public static class AsyncFutureTask extends FutureTask {
public AsyncFutureTask(@NonNull Callable callable) {
super(callable);
}
public AsyncFutureTask execute(@NonNull Executor executor) {
executor.execute(this);
return this;
}
public AsyncFutureTask execute() {
return execute(AsyncTask.THREAD_POOL_EXECUTOR);
}
@Override
protected void done() {
super.done();
//work done, complete or abort or any exception happen
}
}
Second, let's use
try {
Log.d(TAG, new AsyncFutureTask(new Callable() {
@Override
public String call() throws Exception {
//throw Exception in worker thread
throw new Exception("TEST");
}
}).execute().get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
//catch the exception throw by worker thread in main thread
e.printStackTrace();
}