【发布时间】:2021-08-27 04:19:31
【问题描述】:
这是我的角色:
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 是否会关闭。
如何重构上面的代码?
有什么想法吗?
【问题讨论】:
-
它将通过所有可能的路径关闭。无需更改您的代码。
-
您想用“try-catch-resources 中的 return 语句怎么样?”来问什么? “我很清楚 CloseableHttpResponse 是否会关闭,无论是否返回或到达新语句。”这不是已经回答了吗?
-
“X 呢?”不是一个明确的问题。你的问题是那些东西呢?
-
@Sweeper 写错了,我的意思是“我不清楚”。解决了。
-
好吧,当你问对方的意思时,它并没有多大帮助。
标签: java try-catch try-catch-finally