为什么会编译?覆盖方法不是异常的子类

Dou*_*uma 4 java exception

我很难理解为什么以下代码不是异常的子类,但为什么会编译:

class Test 
{
    public void run() throws IOException 
    {
        System.out.println("Test");
    }
}

class SubTest extends Test 
{
    //not a subclass of IOException, still compiles 
    public void run() throws RuntimeException 
    {
        System.out.println("Test from sub");
    }
}

class Sub2Test extends Test 
{
    //not a subclass of IOException, does not compile
    public void run() throws Exception  
    {
        System.out.println("Test from sub");
    }
}
Run Code Online (Sandbox Code Playgroud)

我知道这RuntimeException是一个未经检查的异常,但是我认为规则是它必须是父异常的子类?

孙兴斌*_*孙兴斌 8

想象有一个呼叫者在打电话Test#run。在的声明中Test#run,它说它可能会抛出IOException,因此调用者知道它可以捕获并处理它:

Test test = // it could be instance of SubTest of Sub2Test
try {
   test.run();
} catch (IOException e) {

}
Run Code Online (Sandbox Code Playgroud)

这样就可以了,如果SubTest不抛出IOException,调用者将不会错过任何东西。

但是,如果您抛出一些checked Exceptionlike Sub2Test,因为调用者直到运行时才知道它,所以被调用者无法捕获和处理它。因此,不应对其进行编译。