Java 7 新特性之try-with-resources实践理解
想象这么一个情景,我们需要使用一个资源,在使用完之后需要关闭该资源,并且使用该资源的过程中有可能有异常抛出。此时我们都会想到用try-catch语句,在finally中关闭该资源。此时会有一个问题,如果关闭该资源的时候也抛出了异常呢?见如下例子:
package com.rundong; import java.io.IOException; public class ResourceTest implements AutoCloseable{ @Override public void close() throws IOException { throw new IOException("close Exception"); } }
package com.rundong; import java.io.IOException; import java.sql.SQLException; public class Main { public static void main(String[] args) { try { throwTest(); } catch (SQLException e) { System.out.println("catch SQLException"); e.printStackTrace(); } catch (IOException e) { System.out.println("catch IOException"); e.printStackTrace(); } } static void throwTest() throws SQLException, IOException { ResourceTest resource = null; try { resource = new ResourceTest(); throw new SQLException("the first Exception"); } catch (SQLException e) { System.out.println("catch the first Exception"); // do something throw e; } finally { if (resource != null) resource.close(); } } }
输出结果:
发现什么问题了吗?
finally中抛出的异常将try中抛出的异常覆盖了!我们无法捕获到第一个异常!
Java 7 的解决方式:
package com.rundong; import java.io.IOException; import java.sql.SQLException; public class Main { public static void main(String[] args) { try { throwTest(); } catch (SQLException e) { System.out.println("catch SQLException"); e.printStackTrace(); } catch (IOException e) { System.out.println("catch IOException"); e.printStackTrace(); } } static void throwTest() throws SQLException, IOException { try (ResourceTest resource = new ResourceTest()) { throw new SQLException("the first Exception"); } catch (SQLException e) { System.out.println("catch the first Exception"); // do something throw e; } } }
输出结果:
try-with-resources的写法就能很好的处理这样的情景,它会自动关闭资源,并且如果关闭资源时也抛出了异常,不会覆盖原有异常的抛出。
使用条件:实现了AutoCloseable接口的类。
同时,这也提示着我们,永远不要尝试在finally中抛出异常!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!