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
When I feel the need to handle Exceptions in AsyncTask
properly, I use this as super class:
public abstract class ExceptionAsyncTask extends AsyncTask {
private Exception exception=null;
private Params[] params;
@Override
final protected Result doInBackground(Params... params) {
try {
this.params = params;
return doInBackground();
}
catch (Exception e) {
exception = e;
return null;
}
}
abstract protected Result doInBackground() throws Exception;
@Override
final protected void onPostExecute(Result result) {
super.onPostExecute(result);
onPostExecute(exception, result);
}
abstract protected void onPostExecute(Exception exception, Result result);
public Params[] getParams() {
return params;
}
}
As normal, you override doInBackground
in your subclass to do background work, happily throwing Exceptions where needed. You are then forced to implement onPostExecute
(because it's abstract) and this gently reminds you to handle all types of Exception
, which are passed as parameter. In most cases, Exceptions lead to some type of ui output, so onPostExecute
is a perfect place to do that.