Jeff Shaw Jeff Shaw - 6 months ago 9
Java Question

extracting "throw new exception" into a method causes compile error

I have the following function:

private Box retrieveBox() {
BoxParameter param = new BoxParameter("red", 10, 5, 3);
List<Long> boxIds = boxDao.retrieveByParameter(param);

if (boxIds.isEmpty()) {
// A
logger.warn("box not found");
throw new BoxNotFoundException();
}
if (boxIds.size() > 1) {
// B
logger.warn("multiple boxes found");
throw new MultipleBoxesFoundException();
}

Optional<Box> maybe = boxDao.retrieve(boxIds.get(0));
if (maybe.isPresent()) {
return maybe.get();
}

// C
logger.warn("box not found");
throw new BoxNotFoundException();
}


When I try to refactor the logging and exception into a method called
logWarningAndThrowException()
, I found that:


  • A and B can be refactored

  • if C is extracted into a method, Eclipse prompts that "This method must return a result of type Box"



I'm wondering the reason for that.

Is there a way to extract C into a method?

Answer

Any method with a return type except void must return a value of that type or throw an exception to end method execution.

In your current state your method will throw an exception to end method execution but if you move C part to another method then your retrieveBox method must return a value of type Box for a normal completion.

Hence eclipse is complaining.