这是我的cose:
private ResultSetType makeRequest() {
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);
}
}
我的目标是关闭CloseableHttpResponse
。
这里有几个问题:
try-catch-resources
中的return
语句如何throw new
语句如何
无论到达return
还是thow new
语句,我都不清楚CloseableHttpResponse
是否会关闭。
我如何重构上面的代码?
有什么想法吗?
根据Java语言规范,对现有资源的尝试首先被翻译为:
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中的块最终被转换为try-catch的try
块,并且资源的关闭在finally
块中完成。
这意味着普通try-catch finally语句的语义在这里适用——如果try
块突然完成(即返回或抛出(或正常完成,则finally
块将被执行。具体细节见§14.20.2。您将看到finally
在规范中提到的每种情况下都被执行
因此,总之,即使达到return
或throw
,您的资源也将关闭。