Java.lang.AutoCloseable

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.