Questions tagged [try-with-resources]

The try-with-resources statement is a try statement in Java that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement.

The try-with-resources Statement

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 with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

The following example reads the first line from a file. It uses an instance of BufferedReader to read data from the file. BufferedReader is a resource that must be closed after the program is finished with it:

static String readFirstLineFromFile(String path) throws IOException {
    try (BufferedReader br = Files.newBufferedReader(Paths.get(path))) {
        return br.readLine();
    }
}

In this example, the resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).

Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. The following example uses a finally block instead of a try-with-resources statement:

static String readFirstLineFromFileWithFinallyBlock(String path)
                                                     throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(path));
    try {
        return br.readLine();
    } finally {
        if (br != null) br.close();
    }
}

However, in this example, if the methods readLine and close both throw exceptions, then the method readFirstLineFromFileWithFinallyBlock throws the exception thrown from the finally block; the exception thrown from the try block is suppressed. In contrast, in the example readFirstLineFromFile, if exceptions are thrown from both the try block and the try-with-resources statement, then the method readFirstLineFromFile throws the exception thrown from the try block; the exception thrown from the try-with-resources block is suppressed. In Java SE 7 and later, you can retrieve suppressed exceptions; see the section 'Suppressed Exceptions' for more information.

You may declare one or more resources in a try-with-resources statement. The following example retrieves the names of the files packaged in the zip file zipFileName and creates a text file that contains the names of these files:

public static void writeToFileZipFileContents(String zipFileName,
                                           String outputFileName)
                                           throws java.io.IOException {

    java.nio.charset.Charset charset =
         java.nio.charset.StandardCharsets.US_ASCII;
    java.nio.file.Path outputFilePath =
         java.nio.file.Paths.get(outputFileName);

    // Open zip file and create output file with 
    // try-with-resources statement

    try (
        java.util.zip.ZipFile zf =
             new java.util.zip.ZipFile(zipFileName);
        java.io.BufferedWriter writer = 
            java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
    ) {
        // Enumerate each entry
        for (java.util.Enumeration entries =
                                zf.entries(); entries.hasMoreElements();) {
            // Get the entry name and write it to the output file
            String newLine = System.getProperty("line.separator");
            String zipEntryName =
                 ((java.util.zip.ZipEntry)entries.nextElement()).getName() +
                 newLine;
            writer.write(zipEntryName, 0, zipEntryName.length());
        }
    }
}

In this example, the try-with-resources statement contains two declarations that are separated by a semicolon: ZipFile and BufferedWriter. When the block of code that directly follows it terminates, either normally or because of an exception, the close methods of the BufferedWriter and ZipFile objects are automatically called in this order. Note that the close methods of resources are called in the opposite order of their creation.

The following example uses a try-with-resources statement to automatically close a java.sql.Statement object:

public static void viewTable(Connection con) throws SQLException {

    String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES";

    try (Statement stmt = con.createStatement();
         ResultSet rs = stmt.executeQuery(query)) {

        while (rs.next()) {
            String coffeeName = rs.getString("COF_NAME");
            int supplierID = rs.getInt("SUP_ID");
            float price = rs.getFloat("PRICE");
            int sales = rs.getInt("SALES");
            int total = rs.getInt("TOTAL");

            System.out.println(coffeeName + ", " + supplierID + ", " + 
                               price + ", " + sales + ", " + total);
        }
    } catch (SQLException e) {
        JDBCTutorialUtilities.printSQLException(e);
    }
}

The resource java.sql.Statement used in this example is part of the JDBC 4.1 and later API.

Note: A try-with-resources statement can have catch and finally blocks just like an ordinary try statement. In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.

Suppressed Exceptions

An exception can be thrown from the block of code associated with the try-with-resources statement. In the example writeToFileZipFileContents, an exception can be thrown from the try block, and up to two exceptions can be thrown from the try-with-resources statement when it tries to close the ZipFile and BufferedWriter objects. If an exception is thrown from the try block and one or more exceptions are thrown from the try-with-resources statement, then those exceptions thrown from the try-with-resources statement are suppressed, and the exception thrown by the block is the one that is thrown by the writeToFileZipFileContents method. You can retrieve these suppressed exceptions by calling the Throwable.getSuppressed method from the exception thrown by the try block.

Classes That Implement the AutoCloseable or Closeable Interface

See the Javadoc of the AutoCloseable and Closeable interfaces for a list of classes that implement either of these interfaces. The Closeable interface extends the AutoCloseable interface. The close method of the Closeable interface throws exceptions of type IOException while the close method of the AutoCloseable interface throws exceptions of type Exception. Consequently, subclasses of the AutoCloseable interface can override this behavior of the close method to throw specialized exceptions, such as IOException, or no exception at all.

References: http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

328 questions
173
votes
8 answers

Correct idiom for managing multiple chained resources in try-with-resources block?

The Java 7 try-with-resources syntax (also known as ARM block (Automatic Resource Management)) is nice, short and straightforward when using only one AutoCloseable resource. However, I am not sure what is the correct idiom when I need to declare…
Natix
  • 13,037
  • 7
  • 49
  • 67
162
votes
5 answers

Try-with-resources in Kotlin

When I tried to write an equivalent of a Java try-with-resources code in Kotlin, it didn't work for me. I tried different variations of the following: try (writer = OutputStreamWriter(r.getOutputStream())) { // ... } But neither works. Does…
Alex
  • 2,537
  • 3
  • 18
  • 24
152
votes
5 answers

How should I use try-with-resources with JDBC?

I have a method for getting users from a database with JDBC: public List getUser(int userId) { String sql = "SELECT id, name FROM users WHERE id = ?"; List users = new ArrayList(); try { Connection con =…
Jonas
  • 97,987
  • 90
  • 271
  • 355
88
votes
2 answers

Am I using the Java 7 try-with-resources correctly

I am expecting the buffered reader and file reader to close and the resources released if the exception is throw. public static Object[] fromFile(String filePath) throws FileNotFoundException, IOException { try (BufferedReader br = new…
Cheetah
  • 12,515
  • 28
  • 93
  • 167
80
votes
8 answers

What is a suppressed exception?

A comment (by user soc) on an answer to a question about tail call optimisation mentioned that Java 7 has a new feature called "suppressed exceptions", because of "the addition of ARM" (support for ARM CPUs?). What is a "suppressed exception" in…
Raedwald
  • 40,290
  • 35
  • 127
  • 207
65
votes
4 answers

Close multiple resources with AutoCloseable (try-with-resources)

I know that the resource you pass with a try, will be closed automatically if the resource has AutoCloseable implemented. So far so good. But what do I do when i have several resources that I want automatically closed. Example with sockets; try…
asmb
  • 845
  • 2
  • 7
  • 10
63
votes
4 answers

Why does try-with-resource require a local variable?

With reference to my question Any risk in a AutoCloseable wrapper for java.util.concurrent.locks.Lock?, I am wondering why the try-with-resource-statement require a named local variable at all. My current usage is as follows: try…
Miserable Variable
  • 27,314
  • 13
  • 69
  • 124
62
votes
6 answers

8 branches for try with resources - jacoco coverage possible?

I've got some code that uses try with resources and in jacoco it's coming up as only half covered. All the source code lines are green, but I get a little yellow symbol telling me that only 4 of 8 branches are covered. I'm having trouble figuring…
Gus
  • 6,132
  • 6
  • 32
  • 53
56
votes
7 answers

What's the purpose of try-with-resources statements?

Java 7 has a new feature called try-with-resources. What is it? Why and where we should use it and where we can take advantage of this feature? The try statement has no catch block which confuses me.
user2589993
53
votes
5 answers

Transaction rollback on SQLException using new try-with-resources block

I have a problem with try-with-resources and I am asking just to be sure. Can I use it, if I need to react on exception, and I still need the resource in catch block? Example given is this: try (java.sql.Connection con = createConnection()) { …
Jan Hruby
  • 1,390
  • 1
  • 12
  • 25
52
votes
4 answers

Try-with-resources and return statements in java

I'm wondering if putting a return statement inside a try-with-resources block prevents the resource to be automatically closed. try(Connection conn = ...) { return conn.createStatement().execute("..."); } If I write something like this will the…
maff
  • 697
  • 1
  • 7
  • 9
50
votes
5 answers

IntelliJ IDE gives error when using Try-Catch with Resources

I am attempting to use JDK 7's "try-catch with resources" statement; IntelliJ highlights my resource line, saying Try-with-resources are not supported at this language level. When I try to compile, I get: java: try-with-resources is not…
48
votes
2 answers

Why write Try-With-Resources without Catch or Finally?

Why write Try without a Catch or Finally as in the following example? protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { …
Umair Hashmi
  • 501
  • 1
  • 4
  • 8
39
votes
5 answers

Try With Resources vs Try-Catch

I have been looking at code and I have seen try with resources. I have used the standard try-catch statement before and it looks like they do the same thing. So my question is Try With Resources vs Try-Catch what are the differences between those,…
computerquest
  • 577
  • 1
  • 4
  • 16
37
votes
3 answers

Java 7 Automatic Resource Management JDBC (try-with-resources statement)

How to integrate the common JDBC idiom of creating/receiving a connection, querying the database and possibly processing the results with Java 7's automatic resource management, the try-with-resources statement? (Tutorial) Before Java 7, the usual…
TPete
  • 1,991
  • 4
  • 23
  • 26
1
2 3
21 22