Search code examples
javaexceptionjls

Implementation method Throws exception but interface method don't define as it throws exception


when implementing an interface, it's perfectly legal for the interface methods not to throw an exception, but the implementation class method can throw Exception.

Interface definition

public interface exceptionNotDefined {
    void doNotThrowException();
}

Implementing class

public class exceptionNotDefinedImpl implements exceptionNotDefined {
    @Override
    public void doNotThrowException() throws RuntimeException{

    }
}

what's the logic behind this, and what part of the Java Language Specification deals with this.


Solution

  • ... what's the logic behind this

    The logic is best described by the word "substitutability".

    When an interface method is declared as "throwing" a checked exception, it is saying that the caller has to deal with the exception (by catching it or by declaring it ... or a supertype).

    When you then implement the method without throwing the exception, the method call is substitutable. A caller which has code to deal with the possibility of the exception can cope if the exception won't be thrown.

    The other wrinkle is that in the implementing class you declared the method as throwing RuntimeException. RuntimeException and its subclasses are unchecked exceptions, and the Java language says that a caller doesn't need to deal with unchecked exceptions. So, in fact, the throws RuntimeException has no practical effect, except for documenting the API designer's intent.


    ... what part of the Java Language Specification deals with this.

    JLS Section 11.2 covers most of this at a high level, and the specific rules about method overriding (including throws clauses) are given in JLS 8.4.8.3.