try-with-resources and AutoCloseable

I thought try-with-resources could only be used for things that would generally generate IOExceptions. It seems that it can be enabled for various classes with AutoCloseable.

About try-with-resources

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished. The try-with-resources statement ensures that each resource is closed at the end of the statement. You can use any object that implements java.lang.AutoCloseable as a resource, including all objects that implement java.io.Closeable.

Oracle Java Documentation https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

In other words, if you implement AutoCloseable, you can support try-with-resources!

About AutoCloseable

An object that can hold a resource (such as a file or socket handle) until it is closed. The close () method of an AutoCloseable object is called automatically when you exit the try-with-resources block where the object is declared in the resource specification header. This structure guarantees a quick release and avoids resource shortage exceptions and errors that might otherwise occur. Included in the java.lang package.

Interface AutoCloseable https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/AutoCloseable.html

I want try-with-resources to automatically close when the try statement ends, Also, implement the AutoCloseable interface for the target resource for which you want a special process to be inserted when closing.

About AutoCloseable and Closeable

Similar to AutoCloseable, there is Closeable. This is an interface that inherits from AutoCloseable and is included in the java.io package. AutoCloseable throws an Exception when an exception occurs, but Closeable throws an IOException.

Most of the classes in the java.io package implement Closeable, so Classes such as FileOutputStream and BufferedReader can be declared with try-with-resources.

use

If you want to release resources automatically with try-with-resources It is used when you want to add other processing when releasing resources.

SampleTryWithResources.java


public class SampleTryWithResources {
    public static void main(String[] args) {

//     Closeable(AutoCloseable)The class that implements
//    try-with-If declared with resources, it will be closed automatically at the end of the try statement.()Is executed.
        try (SampleCloseAble sca = new SampleCloseAble()) {
            System.out.println("Try-With-Resources start");

            System.out.println("Try statement in progress");

            System.out.println("Try-With-Resources end");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class SampleCloseAble implements AutoCloseable {
    @Override
    public void close() throws Exception {
        System.out.println("Close of the Closeable class()Run");
    }
}

sys.out


Try-With-Resources start
Try statement in progress
Try-With-Resources end
Close of the Closeable class()Run

The close method implemented after the processing in the try statement is completed is called. However, note that the close method is called before the catch statement when an exception occurs in the try statement, as shown below.

SampleTryWithResources2.java


public class SampleTryWithResources2 {
    public static void main(String[] args) {

        try (SampleCloseAble sca = new SampleCloseAble()) {
            System.out.println("Try-With-Resources start");

            System.out.println("Try statement in progress");

            throw new Exception();
        } catch (Exception e) {
            System.out.println("Try statement exception end");
            e.printStackTrace();
        }
    }
}

sys.out


Try-With-Resources start
Try statement in progress
Close of the Closeable class()Run
Try statement exception end
java.lang.Exception
	at ...

The order of processing is Processing in Try statement ⇒ AutoCloseable close method ⇒ Processing in catch statement Will be.

Recommended Posts

try-with-resources and AutoCloseable
[Java] Difference between Closeable and AutoCloseable
== and equals