为什么这被认为是未处理的例外?

Joh*_*cés 2 java overriding checked-exceptions

由于未处理的异常,以下代码无法编译,尽管在我看来应该没有问题:

class Car {
    public void drive() throws Exception {
        System.out.println("Driving...");
    }
}

public class Sedan extends Car {
    public void drive() {
        System.out.println("Driving Sedan...");
    }
    public static void main(String[] args) {
        Car c = new Sedan();
        c.drive(); //unhandled exception!
    }
}
Run Code Online (Sandbox Code Playgroud)

编译器是否应该明白,当c.drive()调用重写方法时,不会抛出已检查的异常?为什么仅仅因为引用是Car类型而不是类型Sedan,我们必须将驱动器视为仍然抛出已检查的异常?最重要的方法不是!

Zir*_*con 5

不幸的是,不,这对编译器来说并不明显.

编译器本质上是在查看Car c和调用drive.编译器不知道c指向的对象的运行时类型.因此,它评估方法签名Car.drive(),包括throws Exception.

为了使它更清楚,如果在某些其他方法c中重新分配给SUV仍会抛出此异常的某个对象,该怎么办?在drive调用方法时,编译器无法知道对象的状态.