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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With