try-with-resources
JDK7开始,支持try-with-resources.
public class Savevarargs {
public static void main(String[] args) throws Exception {
try (OneCloseable one = new OneCloseable();
TwoCloseable two = new TwoCloseable()) {
one.foo();
two.foo();
} catch (Exception e) {
System.out.println("bom: " + e.getMessage());
Arrays.stream(e.getSuppressed()).forEach(System.out::println);
}
}
}
class OneCloseable implements AutoCloseable {
public OneCloseable() throws Exception {
// throw new Exception("constructor exception....");
}
public void foo() throws Exception {
throw new Exception("one method exception....");
}
@Override
public void close() throws Exception {
System.out.println("one closing.....");
throw new Exception("one close excep...");
}
}
class TwoCloseable implements AutoCloseable {
public TwoCloseable() throws Exception {
// throw new Exception("constructor exception....");
}
public void foo() throws Exception {
throw new Exception("two method exception....");
}
@Override
public void close() throws Exception {
System.out.println("two closing.....");
throw new Exception("two close excep...");
}
}
- try模块参数是resources,为
final
类型,不能在try-with-resources模块中再进行赋值 - try模块和try-with-resources模块执行如遇异常,将抛出,被catch或者向上抛出。这点和jdk7之前相同
- resource定义:实现了
Closable
或者Autoacloseable
的对象 - try或者try-with-resources执行不管是否遇到异常,将调用
resource.close()
- 多个resources用分号分隔,
close()
调用顺序与创建顺序相反 - 如果在当前
resource.close()
中遇到异常,并且此异常不是第一个,当前异常被抑制e.getSuppressed()
获取被抑制的异常