为什么抛出异常的方法的调用者不必在这种情况下处理异常?

use*_*100 6 java exception-handling interface exception try-catch

请考虑以下界面:

package hf;

public interface BadInterface 
{
    void meth() throws Exception;
}
Run Code Online (Sandbox Code Playgroud)

这由以下类实现:

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.");
    }
}
Run Code Online (Sandbox Code Playgroud)

尽管meth()是抛出异常的方法,但方法meth()的调用者不必处理或声明异常,但程序运行成功.为什么会这样?它是否违反了规则,即每当您调用抛出异常的方法时,您需要捕获异常或声明您自己抛出异常?

Dun*_*nes 7

实现接口方法时,可以声明抛出的次数少于接口中列出异常.

当你打电话new apples().meth(),你调用meth()上的apples实例.编译器知道这不会抛出任何东西,所以你没事.

你做完了:

BadInterface foo = new apples();  // Note: should be Apples (code style)
foo.meth();
Run Code Online (Sandbox Code Playgroud)

那么你需要捕获接口中声明的异常,因为编译器只知道它正在处理一个BadInterface实例.