问题描述
第一段代码可以正常工作,并且不显示任何警告,因为IDE识别出如果我们不返回某些内容,则肯定会引发异常
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;
}
除了在其他方法中引发异常外,该代码执行完全相同的操作的代码失败,因为它在IDE上显示警告,提示我们缺少return语句。
private ResponseEntity<String> callService() throws CustomServiceException {
// some code here...
if(someCondition){
// some code here...
return responseVariable
}else{
handleResponse(SERVICE_ERROR_MESSAGE,500);
}
这是句柄响应方法
private void handleResponse(String message,int responseCode) throws CustomException {
CustomException customException = new CustomException(message,responseCode);
throw customException;
}
我知道我只能在最后返回null,并且永远不会返回null,但是是否存在这样的习惯?
解决方法
我认为这种方式会更清晰(并且可以编译):
} else {
throw buildException(SERVICE_ERROR_MESSAGE,500);
}
private CustomException buildException(String message,int responseCode) {
return new CustomException(message,responseCode);
}
,
我认为,不需要使用handleResponse
这样的方法。
只需打印
throw new CustomException(message,responseCode);
代替
handleResponse(message,responseCode);