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