Java识别从另一个方法抛出的错误



第一个代码块运行良好,没有显示任何警告,因为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上显示了一个警告,即我们缺少返回语句。

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,它永远不会到达那里,但这种糟糕的做法是常见的。

在我看来,这样会更清楚(而且会编译(:

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

相关内容

最新更新