Reputation: 1399
This first block of code works fine and shows no warnings because IDE recognises that if we don't return something we are definitely throwing an exception
private ResponseEntity<String> callService() throws CustomServiceException {
// some code here...
if(someCondition){
// some code here...
return responseVariable
}else{
CustomException customException = new CustomException(SERVICE_ERROR_MESSAGE, 500);
throw customException;
}
This code which does the exact same thing except throws the exception from another method fails as it shows a warning on the IDE that we have a missing return statement.
private ResponseEntity<String> callService() throws CustomServiceException {
// some code here...
if(someCondition){
// some code here...
return responseVariable
}else{
handleResponse(SERVICE_ERROR_MESSAGE, 500);
}
This is the handle response method
private void handleResponse(String message, int responseCode) throws CustomException {
CustomException customException = new CustomException(message, responseCode);
throw customException;
}
I know I could just return null at the very end and it will never get there but is that bad practice is there a common practice for stuff like this.
Upvotes: 1
Views: 49
Reputation: 399
I think, there is no need in such a method as handleResponse
.
Just print
throw new CustomException(message, responseCode);
instead of
handleResponse(message, responseCode);
Upvotes: 0
Reputation: 14656
In my opinion would be clearer this way (and it would compile):
} else {
throw buildException(SERVICE_ERROR_MESSAGE, 500);
}
private CustomException buildException(String message, int responseCode) {
return new CustomException(message, responseCode);
}
Upvotes: 3