Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 904
user3760100 Avatar asked Dec 19 '14 11:12

user3760100


1 Answers

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.

like image 164
Duncan Jones Avatar answered Sep 20 '22 23:09

Duncan Jones