Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throw an exception in doInBackground and catch in onPostExecute

I have an error to be thrown from doInBackground method of my Asynctask. Is it possible? how can I make it such that the exception would be caught by onPostExecute?

like image 995
migs Avatar asked Oct 02 '14 13:10

migs


3 Answers

You cannot throw exceptions across threads.

However, you can catch the exception in doInBackground(), store it somewhere such as a member variable in the asynctask and then handle it in onPostExecute().

like image 145
laalto Avatar answered Sep 24 '22 17:09

laalto


No, you can't throw exception in the background thread.

The much better way is to pass the result returned from the background thread (if its exception message then let it be) to the onPostExecute() method which then should process the result according to the need.

like image 45
My God Avatar answered Sep 20 '22 17:09

My God


You can accomplish this by one of the following three methods:

  1. Store the exception as a local variable of the AsyncTask subclass, and check for it in the onPostExecute() method, as suggested by laalto and Peter Pei Guo. You can query it's class type and perform different tasks depending on the type of exception. AsyncTask guarantees that doing this would be thread-safe.

  2. Change the generic result type to Object and return either the exception or your result from the doInBackground() method, then check the result object's class type in the onPostExecute() method, and cast and work on it as appropriate. This is mostly how FutureTask (which AsyncTask uses internally) implements it's get() method, although it stores it's state in a local variable, as it can't rely on the result type.

  3. Create a holder class for your result that can be constructed to contain either the result or some specific exceptions, define it's get method to return the result type if available and throw the exception otherwise, then set your AsyncTask subclass's generic result type to that class, and catch the exceptions in the onPostExecute() method when obtaining the result from the holder.

like image 28
corsair992 Avatar answered Sep 20 '22 17:09

corsair992