How to set the ExecutionException thrown by AsyncTask's get method?

834 Views Asked by At

According to the official documentation, AsyncTask#get() throws an ExecutionException when an exception occurs in the threaded Task. How can I notify the current AsyncTask that an exception has been thrown in the AsyncTask#doInBackground(Params...) method?

2

There are 2 best solutions below

2
On

The best would be not to use AsyncTask.get() at all because get() is synchronous so you will gain nothing

1
On

You can't.

The ExecutionException is thrown by the Future#get() method that is internally called by AsyncTask#get().

Futures do allow to throw Exceptions within their executed asynchronous block. A call to Future#get() will throw such an Exception encapsulated in an ExecutionException.

AsyncTasks, however, do not allow to throw Exceptions within the AsyncTask#doInBackground() method. Therefore, you can't use this mechanism for your exception handling. This seems to be an architectural design decision.

Disclaimer:

You can probably still throw RuntimeExceptions in your AsyncTask#doInBackground(), leading to a related ExecutionException on AsyncTask#get() ... but you shouldn't ;)

Note:

Are you sure that you want to call AsyncTask#get() and block your calling thread? Calling it from your main/ui thread will cause your user interface to stop being refreshed until your task is finished.