3

I am quite new to Java and Android development. I looked at the code of AsyncTask, and saw the class throws 3 Exceptions:

  • InterruptedException
  • ExecutionException
  • TimeoutException

When I run the execute method on an AsyncTask object, why is it that the compiler complains if I don't catch InterruptedException and ExecutionException, but does not complain about TimeoutException​?

More generally, how do we know which exceptions need to be caught? (Of course I look at the compiler errors and write the missing catch blocks, but I'd like to understand the principal behind it).

Thank you very much!

Example code:
public void test() {
    AsyncTask at = new AsyncTask() {
        @Override
        protected Object doInBackground(Object[] params) {
            return null;
        }
    };

    Object o;
    try {
        o = at.execute().get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }

}

Edit: I checked that TimeoutException is a checked exception (which should be caught). However @NicolasFilotto already answered my question. Thank you all.

Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
  • I checked that TimeoutException is a checked exception. However @NicolasFilotto already answered my question. Thank you all. – syner.cchan Jan 10 '17 at 20:01

1 Answers1

1

The get() method only throws InterruptedException, ExecutionException and CancellationException that is why you don't need to catch TimeoutException in your case, only the method get(long timeout, java.util.concurrent.TimeUnit unit) throws the 3 exceptions listed above and CancellationException which is the counterpart of get() but with a timeout.

NB: CancellationException is an unchecked exception so it doesn't need to be caught.

Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122