Search code examples
javaoverridingchecked-exceptions

Why is this considered an unhandled exception?


The following code doesn't compile because of an unhandled exception, though it seems to me like there should be no problem:

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!
    }
}

Shouldn't it be obvious to the compiler that when the overriding method c.drive() is called, a checked exception will not be thrown? Why is it that just because the reference is of type Car instead of type Sedan, we have to treat drive as if it still throws a checked exception? The overriding method doesn't!


Solution

  • Unfortunately, no, it's not obvious to the compiler.

    The compiler is essentially looking at Car c and the call to drive. The compiler has no knowledge of the run-time type of the object that c is pointing to. Because of this, it evaluates the method signature of Car.drive(), which includes the throws Exception.

    To make it clearer, what if in some other method c was reassigned to some SUV object which still throws this exception? The compiler has no way to know the state of the object by the time the drive method is called.