java try的用法_Java中try()catch{}的使用方法

今天撸代码的时候发现了一段这样的代码

try(

Connection conn=DriverManager.getConnection(url,user,pass);

Statement stmt=conn.createStatement()

) {boolean hasResultSet=stmt.execute(sql);

}

和平常见的不一样,我们平常见的是这样的

try{

fis=new FileInputStream("src\\com\\ggp\\first\\FileInputStreamDemo.java");byte[]bbuf=new byte[1024];int hasRead=0;while((hasRead=fis.read(bbuf))>0){

System.out.println(new String(bbuf,0,hasRead));

}

}catch(IOException e){

e.printStackTrace();

}finally{try{

fis.close();

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}

如果{}中的代码块出现了异常,会被catch捕获,然后执行catch中的代码,接着执行finally中的码,其中catch中的代码有了异常才会被执行,finally中的代码无论有没有异常都会被执行,

而第一种情况的()中的代码一般放的是对资源的申请,如果{}中的代码出项了异常,()中的资源就会被关闭,这在inputstream和outputstream的使用中会很方便例如

private static voidcustomBufferStreamCopy(File source, File target) {try (InputStream fis = newFileInputStream(source);

OutputStream fos= newFileOutputStream(target)){byte[] buf = new byte[8192];inti;while ((i = fis.read(buf)) != -1) {

fos.write(buf,0, i);

}

}catch(Exception e) {

e.printStackTrace();

}

}

从网上查阅资料得知从 Java 7 build 105 版本开始,Java 7 的编译器和运行环境支持新的 try-with-resources 语句,称为 ARM 块(Automatic Resource Management) ,自动资源管理。

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

带有resources的try语句声明一个或多个resources。resources是在程序结束后默认掉resources.close(),关闭的资源对象。try-with-resources语句确保在语句末尾关闭每个resources。任何实现java.lang.AutoCloseable,包括实现了java.io.Closeable的类,都可以作为resources使用

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值