Given:

class FuelNotAvailException extends Exception {
}

class Vehicle {

    void ride() throws FuelNotAvailException { //line n1
        System.out.println("Happy Journey!");
    }
}

class SolarVehicle extends Vehicle {

    public void ride() throws Exception { //line n2
        super.ride();
    }
}

and the code fragment:

public static void main(String[] args) throws FuelNotAvailException, Exception {
    Vehicle v = new SolarVehicle();
    v.ride();
}

Which modification enables the code fragment to print Happy Journey!?

A. Replace line n1 with public void ride() throws FuelNotAvailException {
B. Replace line n1 with protected void ride() throws Exception {
C. Replace line n2 with void ride() throws Exception {
D. Replace line n2 with private void ride() throws FuelNotAvailException {

题解

FuelNotAvailException 继承 Exception,属于 checked exception。

题目原先的程序会在 line n2 编译失败,因为 SolarVehicle 的 ride 方法覆写了 Vehicle 的 ride 方法,Vehicle 的 ride 方法会抛出 FuelNotAvailException,所以 SolarVehicle 的 ride 方法只能不抛出例外、抛出 unchecked exception 或是抛出 FuelNotAvailException 或其子例外。

选项 A,对编译问题没有帮助。

选项 B,正确。

选项 C,对编译问题没有帮助。

选项 D,可见度需要大于等于 default,使用 private 会编译错误。