Java SE7新特性之try-with-resources语句(二)

2014-11-24 07:20:16 · 作者: · 浏览: 1
ith-resources 语句可以像普通的 try 语句那样有 catchfinally 块。在try-with-resources 语句中, 任意的 catch 或者 finally 块都是在声明的资源被关闭以后才运行。

被抑制的异常

try-with-resources 语句关联的代码块可能会抛出异常。在 writeToFileZipFileContents这个例子中, 当试图关闭 ZipFileBufferedWriter 对象时,try 块可能会抛出一个异常,并且 try-with-resources 语句可能抛出多达两个异常 。如果 try 块抛出异常并且 try-with-resources 语句抛出一个或多个异常,那么从 try-with-resources 语句中抛出的异常将会被抑制, 并且块抛出的异常是由 writeToFileZipFileContents 方法抛出的那一个。你可以通过调用由 try块抛出的异常的Throwable.getSuppressed 方法检索这些被抑制的异常信息

实现了AutoCloseable 或 Closeable 接口的类

参见 AutoCloseableCloseable 接口的Javadoc可以看到实现了两者当中的任何一个接口的类集Closeable 接口继承了 AutoCloseable 接口。 Closeable接口的 close 方法抛出IOException 类型的异常而 AutoCloseable 接口的 close 方法抛出 Exception 类型的异常因此, subclasses of the AutoCloseable 接口的子类可以重写 close 方法的这个行为来抛出指定的异常,例如 IOException, 或者没有异常。


本文翻译自Oracle官方文档http://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html