Java:尝试用return和throw语句捕获资源
这是我的理由:Java:尝试用return和throw语句捕获资源,java,try-catch,try-catch-finally,Java,Try Catch,Try Catch Finally,这是我的理由: private resultsetype makeRequest(){ try(CloseableHttpResponse response=this.sendRequest(请求)){ String responseBody=IOUtils.toString( response.getEntity().getContent(), 标准字符集.UTF_8 ); if(HttpStatus.SC_OK==response.getStatusLine().getStatusCode(
private resultsetype makeRequest(){
try(CloseableHttpResponse response=this.sendRequest(请求)){
String responseBody=IOUtils.toString(
response.getEntity().getContent(),
标准字符集.UTF_8
);
if(HttpStatus.SC_OK==response.getStatusLine().getStatusCode()){
//做点什么;
返回。。。
}否则{
抛出新的LoaderSystemFault(LoaderConstants.ErrorCodes.Err002,“与服务器的通信错误(状态代码:{0}/请求:{1}/响应:{2})”,response.getStatusLine().getStatusCode(),请求,响应库);
}
}catch(IOException | jaxbeexception e){
抛出新的LoaderSystemFault(LoaderConstants.ErrorCodes.Err002,“与服务器的通信错误(状态代码:{0}/请求:{1}/响应:{2})”,response.getStatusLine().getStatusCode(),请求,响应库);
}
}
我的目标是关闭CloseableHttpResponse
这里有几个问题:
- 那么
中的try catch resources
语句呢return
- 抛出新的语句怎么样
CloseableHttpResponse
是否会关闭,无论return
还是thow new
语句是否会关闭
我如何重构上述代码
有什么想法吗?根据,尝试使用您现有的资源首先会转化为:
try {
try (CloseableHttpResponse response = this.sendRequest(request)) {
String responseBody = IOUtils.toString(
response.getEntity().getContent(),
StandardCharsets.UTF_8
);
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
// do something;
return ...
} else {
throw new LoaderSystemFault(LoaderConstants.ErrorCodes.ERR_002, "Communication error with Servei Territorial (status-code: {0} / request: {1} / response: {2})", response.getStatusLine().getStatusCode(), request, responseBody);
}
}
} catch (IOException | JAXBException e) {
throw new LoaderSystemFault(LoaderConstants.ErrorCodes.ERR_002, "Communication error with Servei Territorial (status-code: {0} / request: {1} / response: {2})", response.getStatusLine().getStatusCode(), request, responseBody);
}
内部的try with resources现在是一个基本的try with resources语句,翻译如下:
{
final CloseableHttpResponse response = this.sendRequest(request);
Throwable #primaryExc = null;
try {
// everything in your try block
} catch (Throwable #t) {
#primaryExc = #t;
throw #t;
} finally {
if (response != null) {
if (#primaryExc != null) {
try {
response.close();
} catch (Throwable #suppressedExc) {
#primaryExc.addSuppressed(#suppressedExc);
}
} else {
response.close();
}
}
}
}
需要注意的重要一点是,原始try with resources中的块被转换为try catch finally的try
块,资源的关闭在finally
块中完成
这意味着正常的try-catch-finally语句的语义在这里适用-如果try
块突然完成(即返回或抛出),或者如果它正常完成,那么finally
块将被执行。有关详细信息,请参阅。您将看到,最终在规范中提到的每种情况下都会执行
因此,总之,即使达到返回
或抛出
,您的资源也将关闭。它将通过所有可能的路径关闭。不需要更改您的代码。您想问什么“try-catch资源中的return语句如何?”这不是已经由“我很清楚,无论是否到达return或新语句,CloseableHttpResponse是否将关闭”回答的吗?“X如何?”不是一个明确的问题。你的问题是这些东西怎么办?@Sweeper写错了,我的意思是“我不清楚”。解决了。当你问对方你的意思时,没有多大帮助。