英文:
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论