Robert
Robert

Reputation: 8683

Callable.call declared to throw Exception

When I declare my Callable.call() method to throw Exception, the compiler (both Eclipse Neon and Oracle's javax 1.8.0_131 with -Xlint:all) remains silent, but when I declare it to throw IOException, the compiler sees that this can never happen.

public class CallableException implements java.util.concurrent.Callable<Void> {
    @Override
    public Void call() throws Exception {
        // no warning -- why not?
        return null;
   }
}

public class CallableIoException implements java.util.concurrent.Callable<Void> {
    @Override
    public Void call() throws java.io.IOException {
        // warning: declared exception IOException is not actually thrown
        return null;
   }
}

Why don't I get a warning for the throws Exception throw specification?

I understand that Callable.call() is declared to throw Exception, but I can make my implementation throw less than the interface allows.

Upvotes: 2

Views: 1325

Answers (1)

TM00
TM00

Reputation: 1390

I believe this happens because when you state that an IOException will be thrown, the compiler actually expects and checks for that specific type of Exception to occur in the method. This may be by calling a function known to throw it. Exceptions that the compiler checks for are known as checked exceptions. See javadoc for more information.

If you just declare a regular Exception, the compiler doesn't bother because any piece of code could potentially produce an Exception. These are known as unchecked exceptions and are of RuntimeException decent.

In summary: When you specify a specific Exception (not RuntimeException or subclass of it) to be thrown. The compiler verifies it's possibility and gives a warning if it cannot happen. Which then means the throws clause is unnecessary.

Upvotes: 2

Related Questions