try-with-resources
1.定义:在JDK7出现的一种代替finally来关闭资源的异常处理方式
2.基本形式:
try(resources-specification){ //使用资源 }
解释:resources-specification声明初始化资源,可以在这里声明
多个对象,用分号隔开就好;当try语句结束时,资源会自动释放;
try-with-resources也可以不包含catch和finally语句;
局限:并非所有的资源都可以自动关闭,只有实现了java.lang.AutoCloseable
接口的那些资源才可以自动关闭;该接口是JDK7新增的,定义了close方法;
java.io.Closeable接口继承了java.lang.AutoCloseable接口,这两个接口
被所有的流类实现,包括FileInputStream和FileOutputStream。因此在使用
流时,可以使用try-with-resources语句
ep:
完整代码:
package com.ahuiby.test; class Dog implements AutoCloseable{ public Dog(){ System.out.println("The Dog is created."); }; public void init() throws Exception{ System.out.println("The Dog is inited."); throw new Exception(); } @Override public void close(){ System.out.println("The Dog is closed."); } } class Cat implements AutoCloseable{ public Cat(){ System.out.println("The Cat is created."); }; public void init() throws Exception{ System.out.println("The Cat is inited."); throw new Exception(); } @Override public void close(){ System.out.println("The Cat is closed."); } } public class Test { public static void main(String[] args) { // TODO Auto-generated method stub try(Dog d=new Dog(); Cat c=new Cat()){ d.init(); c.init(); }catch(Exception e){ System.out.println("deal this Exception."); }finally{ System.out.println("All is closed!"); } } }
运行结果:
The Dog is created. The Cat is created. The Dog is inited. The Cat is closed. The Dog is closed. deal this Exception. All is closed!
注意:
a)非流类必须实现AutoCloseable接口
b)try(初始化对象)