Search code examples
javaspringexceptiondesign-patternscoding-style

Java recognise an error being thrown from another method


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.


Solution

  • 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);
    }