java.lang.AutoCloseableAndjava.io.Closeable
public interface AutoCloseable { void close() throws Exception;}public interface Closeable extends AutoCloseable { public void close() throws IOException;}
java.lang.AutoCloseableis JDK7 the new interface that is added
- Autocloseable interface to
try-with-resource provide support
java.io.Closeableis JDK5 the interface that is added. Starting with JDK7, Closeable expanded the autocloseable. Therefore, in JDK7, all classes that implement the Closeable interface also implement the Autocloseable interface.
- Autocloseable is an interface at a higher level of abstraction, not necessarily on IO, so the exception that is thrown by the Close method inside it is Exception, not ioexception.
- The closable is only used as an IO stream, so the exception thrown by the Close method is IOException.
Custom Autoclosable Implementation
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..."); } }}
Resources
- Explore Java Io's autocloseable,closeable and flushable interfaces
- Autocloseable & Closable
Java.lang.AutoCloseable