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 ...

Get Asynchronous Android now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.