0

This code compiles without an error:

private FutureTask<MessageSource> loadingTask(final Locale locale)
{
    return new FutureTask<MessageSource>(new Callable<MessageSource>()
    {
        @Override
        public MessageSource call()
            throws IOException
        {
            return loader.load(locale);
        }
    });
}

But the Callable interface defines this:

public V call()
    throws Exception;

How come I can declare that my override throws IOException?

Note: I have already seen, and exploited that, with Guava's CacheLoader for instance.

fge
  • 119,121
  • 33
  • 254
  • 329

2 Answers2

4

The short answer: you can do that because an IOException is-a Exception.

public V call() throws Exception

means "this method can throw an Exception and no other checked exception!".

If you now override this method like this:

public MessageSource call() throws IOException

You're effectively saying "we would be allowed to throw any Exception but we voluntary restrict ourself to just a subset: IOException and its children".

You could even do this:

public Something call()

with no throws at all: "we would be allowed to throw any Exception, but I promise that we throw no checked exceptions at all!"

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
2

When overriding a method that throws some exceptions, the overriden method must throw the same exceptions as the overriding method or some of their superclasses.

This is described in the JLS #8.4.8.3:

suppose that B is a class or interface, and A is a superclass or superinterface of B, and a method declaration n in B overrides or hides a method declaration m in A. Then:

  • If n has a throws clause that mentions any checked exception types, then m must have a throws clause, or a compile-time error occurs.
  • For every checked exception type listed in the throws clause of n, that same exception class or one of its supertypes must occur in the erasureof the throws clause of m; otherwise, a compile-time error occurs.

(where n overrides m)

assylias
  • 321,522
  • 82
  • 660
  • 783