標籤:detail china led exce str dna flush closeable 參考
java.lang.AutoCloseable和java.io.Closeable
public interface AutoCloseable { void close() throws Exception;}public interface Closeable extends AutoCloseable { public void close() throws IOException;}
java.lang.AutoCloseable是JDK7添加的新介面
- AutoCloseable介面對
try-with-resource提供支援
java.io.Closeable是JDK5添加的介面。從JDK7開始,Closeable擴充了AutoCloseable。因此,在JDK7中,所有實現了Closeable介面的類也都實現了AutoCloseable介面。
- AutoCloseable 是一個更高抽象層次的介面,不一定用在 IO 上,所以它裡面的 close 方法拋出的異常是 Exception,而非 IOException。
- Closable 只用作 IO 流上,所以 close 方法拋出的異常是 IOException。
自訂AutoClosable 實現
public class TryWithResource implements AutoCloseable { @Override public void close() throws Exception { StackTraceElement stack[] = Thread.currentThread().getStackTrace(); for (StackTraceElement ste : stack) { System.out .println("called by " + ste.getClassName() + "." + ste.getMethodName() + " / " + ste.getFileName()); } } public static void main(String[] args) { try (TryWithResource twr = new TryWithResource()) { System.out.println("use end..."); throw new Exception("xxx"); } catch (Exception e) { System.out.println("close error..."); } }}
參考資料
- 探究java IO之AutoCloseable,Closeable和Flushable介面
- AutoCloseable & Closable
java.lang.AutoCloseable