Return to site

☕🎓JAVA CERTIFICATION QUESTION:

· java,ocp

Given these two exception classes:

class BatteryException extends Exception { }
class FuelException extends Exception { }

And the following Car class:

Which statement is correct about the start() method? Choose one.

* It may return BadBattery or an empty string.

* It can only return an empty string.

* It may throw FuelException.

* It will cause a compilation error because FuelException is not handled.

#java #certificationquestion #ocp

 

 

 

 

Answer: It can only return an empty string.

Looking at the code, notice that there are two domain-specific exceptions related to the battery and the fuel.

They’re direct subtypes of Exception, which means that they are checked exceptions.

If such an exception might be thrown by a method, it must be declared in the throws clause of that method.

The usual way to handle an exception inside a method is to use a try-catch structure and provide a catch block that names the exception, or a parent type of that exception.

In this code, there’s a catch block for the BatteryException but not for the FuelException.

Given that the method does not declare throws FuelException, you might expect the compiler to refuse to compile the code.

However, if you think a bit deeper on this, you should realize that the finally block executes return "".

This does exactly what it says: No matter how the code reaches the finally block, the result is that the method will return an empty string.

No exceptions will be thrown; indeed, any FuelException that might arise will simply be abandoned.

In other words, because FuelException is never thrown by the method, it’s not necessary to declare it in a throws clause.

This phenomenon is called: "abrupt completion".

The return statement always completes abruptly.

So the return statement in the finally block supersedes the behaviors of the try/catch exception handling.

You know that the return "" in the finally block is always executed because there are no paths through the method that do not enter the try construct.

Putting this together with the specification excerpts above, you can see that the only possible result of executing the method is abrupt completion, which returns an empty string.