try-with-resources

try-with-resources is a syntax added in Java 7, which is more concise and safer than the previous try-catch-finally.

Let's take a look at the differences between them:

grammar:

try-with-resources supports automatic closing of resources in reverse order

try (multiple resources){
    Business code where exceptions may occur;
}

try-catch-finally

try{
     Business code where exceptions may occur;
} catch (caught exception){
     
}fianlly{
     close resource
}

 

Close io original try-catch-finally:

1 static String readFirstLineFromFileWithFinallyBlock(String path)
2                                                     throws IOException {
3     BufferedReader br = new BufferedReader(new FileReader(path));
4     try {
5         return br.readLine();
6     } finally {
7         if (br != null) br.close();
8     }
9 }

In fact, an exception may still occur in finally, so the method still has to throw an exception (just in case)

static String readFirstLineFromFile(String path) throws IOException {
    try (BufferedReader br =
                  new BufferedReader(new FileReader(path))) {
        return br.readLine();
    }
}
Take a look at a set of comparisons:
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());
        }
    }
}
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);
    }
}

 

Note: The try-with-resources statement can also have catch and finally blocks like a normal try statement. In a try-with-resources statement, any catch and finally blocks are executed after all declared resources have been closed.
 
suppressed exception
 
The block of code associated with the try-with-resources statement may throw an exception. In the writeToFileZipFileContents example, exceptions may be thrown in the try block, and up to two exceptions may be thrown in the try-with-resources statement when trying to close the ZipFile and BufferedWriter objects. If an exception is thrown in the try block and one or more exceptions are thrown in the try-with-resources statement, then the exception thrown in the try-with-resources statement is suppressed and ends up in writeToFileZipFileContents The exception thrown by the method is the one thrown in the try block. You can retrieve the suppressed exception via the Throwable.getSuppressed method of the exception thrown by the try block.
 
A class that implements the AutoCloseable or Closeable interface
 
Look at  the javadoc of the interface AutoCloseable  and  Closeable  see what classes implement them. The Closeable interface inherits the AutoCloseable interface. The difference is that the close method of the Closeable interface throws an IOException, and the close method of the AutoCloseable interface throws an Exception. Therefore, subclasses of AutoCloseable can override the behavior of the close method, throwing specified exceptions, such as IOException, or even not throwing exceptions.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325020757&siteId=291194637