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

huangapple go评论75阅读模式
英文:

Java recognise an error being thrown from another method

问题

第一个代码块可以正常工作并且没有警告,因为IDE识别到如果我们没有返回值,肯定会抛出异常。

第二个代码块完成相同的操作,只是将异常从另一个方法抛出,但是它会在IDE上显示一个警告,指示缺少返回语句。

以下是 handleResponse 方法的代码:

private void handleResponse(String message, int responseCode) throws CustomException {
   CustomException customException = new CustomException(message, responseCode);
   throw customException;
}

我知道我可以只在最后返回 null,这样代码永远不会执行到那里,但这种做法是否不好,是否有一种常见的做法来处理这种情况。

英文:

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.

答案1

得分: 3

根据我的看法,这样会更清晰(并且会编译通过):

} else {
    throw buildException(SERVICE_ERROR_MESSAGE, 500);          
}

private CustomException buildException(String message, int responseCode) {
    return new CustomException(message, responseCode);
}
英文:

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

答案2

得分: 0

我认为,并不需要像 handleResponse 这样的方法。<br>
只需打印:

throw new CustomException(message, responseCode);

而不是:

handleResponse(message, responseCode);
英文:

I think, there is no need in such a method as handleResponse.<br>
Just print

throw new CustomException(message, responseCode);

instead of

handleResponse(message, responseCode);

huangapple
  • 本文由 发表于 2020年10月13日 20:01:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/64334852.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定