Exam 1z0-809 All QuestionsBrowse all questions from this exam
Question 240

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();

}

Happy Journey!?

Which modification enables the code fragment to print

line n1 with public void ride() throws FuelNotAvailException {

    Correct Answer:

    To enable the code to print 'Happy Journey!', the method signature in the subclass SolarVehicle must conform to the method signature in the superclass Vehicle. In Java, when overriding a method, the subclass method cannot throw broader checked exceptions than the superclass method. Since the method in the superclass throws FuelNotAvailException, the overriding method in the subclass must throw FuelNotAvailException or no checked exception at all. Therefore, replacing line n2 with `void ride() throws FuelNotAvailException {` will fix the issue because this makes sure that the SolarVehicle's ride method throws the same exception as the Vehicle's ride method, thereby respecting the exception hierarchy and allowing the code to compile and run as expected.

Discussion
rameasyOption: A

Ans: A. Tested.

adnano1234Option: A

Replaces line n1 with public void ride() throws FuelNotAvailException {

thetechOption: A

Answer is A. Tested.

asdfjhfgjuaDCVOption: A

A is the correct answer

steefaandOption: A

A is correct.

iSnoverOption: A

Answer is A. Tested.

johnchen88Option: D

The Correct Answer should be D. Replace (replace n2 with throws FuelNotAvailException, and replace super ride () with (super.ride ())