Why should the calling method that throws the exception not handle the exception in this situation?

Consider the following interface:

package hf; public interface BadInterface { void meth() throws Exception; } 

which is implemented by the following class:

 package hf; public class apples implements BadInterface { public static void main(String[] args) { new apples().meth(); } public void meth() { System.out.println("Ding dong meth."); } } 

Although the meth () method is a method that throws an exception, the caller of the meth () method should not handle or throw an exception, and yet the program succeeds. Why is this so? Does this violate the rule that whenever you call a method that throws an exception, you need to catch the exception or declare that you yourself have selected the exception?

+6
source share
2 answers

When you implement an interface method, you are allowed to declare that you throw fewer exceptions than what is specified in the interface.

When you call new apples().meth() , you call meth() on the apples instance. The compiler knows that it doesn't throw anything, so you're fine.

You made:

 BadInterface foo = new apples(); // Note: should be Apples (code style) foo.meth(); 

then you will need to catch the exception declared in the interface, because the compiler only knows about this with the BadInterface instance.

+7
source

According to JLS Requirements for Overriding and Hiding :

B is a class or interface, A is a superclass or superinterface B, and the declaration m2 in B overrides or hides the declaration m1 of the method in A. Then:

For each type of exception checked in the throws of m2 clause, the same class of exceptions or one of its supertypes must occur in erasing (ยง4.6) the position of the m1 throws; otherwise, a compilation time error occurs.

means that the extension method can only have a stronger exclusion policy. If it has weaker restrictions, then this method cannot be used instead of the base method and violates the concept of redefinition.

0
source

Source: https://habr.com/ru/post/979914/


All Articles