简体   繁体   中英

Why does the caller of the method that throws an exception not have to 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 meth() is a method that throws an exception, the caller of the method meth() is not having to handle or declare the exception and yet the program runs successfully. Why is this the case? Does it not violate the rule that whenever you call a method that throws an exception, you need to catch the exception or declare that you throw the exception yourself?

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

When you call new apples().meth() , you are invoking meth() on an apples instance. The compiler knows this doesn't throw anything, so you are fine.

Had you done:

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

then you would need to catch the exception declared in the interface, because the compiler only knows it's dealing with a BadInterface instance.

According to JLS Requirements in Overriding and Hiding :

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

For every checked exception type listed in the throws clause of m2, that same exception class or one of its supertypes must occur in the erasure (§4.6) of the throws clause of m1; otherwise, a compile-time error occurs.

Means that extending method can have only a stronger exception policy. If it has a weaker restrictions, than such method can't be used instead of a base method and it breaks concept of overriding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM