Java:尝试用return捕获资源并抛出新语句



这是我的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在规范中提到的每种情况下都被执行

因此,总之,即使达到returnthrow,您的资源也将关闭。

相关内容

  • 没有找到相关文章

最新更新