admin管理员组文章数量:1516870
try
使用传统的try-catch,需要手动关闭打开的资源,finally中还需要对资源先进行判空再关闭,比较繁琐,示例代码如下
private void correctWriting() throws IOException {DataOutputStream out = null;try {out = new DataOutputStream(new FileOutputStream("data"));out.writeInt(666);out.writeUTF("Hello");} finally {if (out != null) {out.close();}} }
try-with是JDK7后推出的语法糖,可以自动关闭打开的资源,如果想使用try-with,资源类必须实现AutoCloseable接口
@Test
public void getCourses() {String url="jdbc:mysql:///cgb2109";
//使用try with语法糖需要在try的括号中打开资源,如果有多个资源,用分号间隔try (Connection conn=DriverManager.getConnection(url,"root","root");Statement state=conn.createStatement();){ResultSet res=state.executeQuery("select * from courses");while(res.next()){for (int i = 1; i <=3; i++) {System.out.print(res.getObject(i)+"\t");}System.out.println();}} catch (SQLException throwables) {throwables.printStackTrace();}
如何查看try with是否有自动执行close(),可以让某个类实现AutoCloseable接口,并重写其中的close方法,如果自动关闭资源,会执行这个重写的close方法,示例代码如下
public class Test2 {public static void main(String[] args) {try(close_demo cd=new close_demo()){}catch (Exception e){e.printStackTrace();}}
}
class close_demo implements AutoCloseable{@Overridepublic void close() throws Exception {//重写此方法后,在try with类的资源使用结束后会自动调用close方法来关闭资源System.out.println("关闭");}
}
本文标签: try
版权声明:本文标题:try 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.betaflare.com/web/1687863563a150685.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。


发表评论