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
?
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()
.
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.
You can accomplish this by one of the following three methods:
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.
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.
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.
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