Java try-catch-resources中return/throw下资源关闭问题及代码重构
问题解答
try-with-resources的资源关闭逻辑
- try代码块内的return语句不会影响资源关闭:Java语法明确规定,声明在try-with-resources括号内的
AutoCloseable实现类,会在return执行前优先调用close()方法释放资源,再返回结果。 - 代码块内主动抛出异常也不会影响资源关闭:无论异常是在try块内主动抛出,还是代码执行过程中意外触发,都会先执行资源的
close()方法,再走后续的异常抛出、catch捕获逻辑。
注意:你提供的原始代码存在编译错误,response和responseBody的作用域仅在try块内部,catch块中直接访问这两个变量会编译失败。
重构优化思路
- 修复编译问题:把需要在异常信息中输出的状态码、响应体提前提取到try块外声明,设置默认值,避免作用域问题。
- 消除重复代码:合并两处抛自定义异常的逻辑,避免重复编写错误描述。
- 增加空安全校验:读取响应体前先判断
response.getEntity()是否为空,避免触发空指针异常。 - 保留异常栈信息:捕获IO、JAXB异常后,把原始异常作为参数传入自定义异常,避免丢失根因栈信息,方便后续排查问题。
重构后代码示例
private ResultSetType makeRequest() { // 提前声明异常需要的参数,设置默认值 int statusCode = -1; String responseBody = ""; try (CloseableHttpResponse response = this.sendRequest(request)) { statusCode = response.getStatusLine().getStatusCode(); if (response.getEntity() != null) { responseBody = IOUtils.toString( response.getEntity().getContent(), StandardCharsets.UTF_8 ); } if (HttpStatus.SC_OK == statusCode) { // 原有业务逻辑 return ...; } // 非200状态统一抛异常 throw new LoaderSystemFault(LoaderConstants.ErrorCodes.ERR_002, "Communication error with Servei Territorial (status-code: {0} / request: {1} / response: {2})", statusCode, 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})", statusCode, request, responseBody, e); } }
内容的提问来源于stack exchange,提问作者Jordi
相关产品推荐
相关产品推荐

