微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Java识别从其他方法抛出的错误

如何解决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上显示警告,提示我们缺少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);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。