Handling exceptions
The callback methods defined by AsyncTask
dictate that we cannot throw checked exceptions, so we must wrap any code that throws checked exceptions with try/catch blocks. Unchecked exceptions that propagate out of AsyncTask
's methods will crash our application, so we must test carefully and handle these if necessary.
For the callback methods that run on the main thread—onPreExecute()
, onProgressUpdate()
, onPostExecute()
, and onCancelled()
—we can catch exceptions in the method and directly update the user interface to alert the user.
Of course, exceptions are likely to arise in our doInBackground()
method too, as this is where the bulk of the work of AsyncTask
is done, but unfortunately, we can't update the user interface from doInBackground()
. A simple solution is to have doInBackground()
return an object that may contain either the result or an exception. First we are going to create a generic class for storing the result of an operation and a member to store an exception...