Shocould. close () be put in finally block or not?

Source: Internet
Author: User

The following are 3 different ways to close a output writer. the first one puts close () method in try clause, the second one puts close in finally clause, and the third one uses a try-with-resources statement. which one is the right or the best?

=  FileWriter("out.txt", "the text"
PrintWriter out = =  FileWriter("out.txt", "the text" (out != 
 (PrintWriter out2 =  FileWriter("out.txt", "the text"

 

Answer

Because the Writer shocould be closed in either case (exception or no exception), close () shocould be put in finally clause.

From Java 7, we can useTry-with-resourcesStatement. Why?

The try-with-resources Statement

Thetry-With-resources statement istryStatement that declares one or more resources.ResourceIs an object that must be closed after the program is finished with it.try-With-resources statement ensures that each resource is closed at the end of the statement. Any object that implementsjava.lang.AutoCloseable, Which includes all objects which implementjava.io.Closeable, Can be used as a resource.

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

static String readFirstLineFromFile(String path) throws IOException {    try (BufferedReader br =                   new BufferedReader(new FileReader(path))) {        return br.readLine();    }}

In this example, the resource declared intry-With-resources statement isBufferedReader. The declaration statement appears within parentheses immediately aftertryKeyword. The classBufferedReader, In Java SE 7 and later, implements the interfacejava.lang.AutoCloseable. BecauseBufferedReaderInstance is declared intry-With-resource statement, it will be closed regardless of whethertryStatement completes normally or abruptly (as a result of the methodBufferedReader.readLineThrowingIOException).

Prior to Java SE 7, you can usefinallyBlock to ensure that a resource is closed regardless of whethertryStatement completes normally or abruptly. The following example usesfinallyBlock instead oftry-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 methodsreadLineAndcloseBoth throw exceptions, then the methodreadFirstLineFromFileWithFinallyBlockThrows the exception thrown fromfinallyBlock; the exception thrown fromtryBlock is suppressed. In contrast, in the examplereadFirstLineFromFile, If exceptions are thrown from bothtryBlock andtry-With-resources statement, then the methodreadFirstLineFromFileThrows the exception thrown fromtryBlock; the exception thrown fromtry-With-resources block is suppressed. In Java SE 7 and later, you can retrieve suppressed limits; see the section Suppressed limits for more information.

You may declare one or more resources intry-With-resources statement. The following example retrieves the names of the files packaged in the zip filezipFileNameAnd 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,try-With-resources statement contains two declarations that are separated by a semicolon:ZipFileAndBufferedWriter. When the block of code that directly follows it terminates, either normally or because of an exception,closeMethods ofBufferedWriterAndZipFileObjects are automatically called in this order. Note thatcloseMethods of resources are called inOppositeOrder of their creation.

The following example usestry-With-resources statement to automatically closejava.sql.StatementObject:

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 resourcejava.sql.StatementUsed in this example is part of the JDBC 4.1 and later API.

Note:try-With-resources statement can havecatchAndfinallyBlocks just like an ordinarytryStatement. Intry-With-resources statement, anycatchOrfinallyBlock is run after the resources declared have been closed.

Suppressed Exceptions

An exception can be thrown from the block of code associated withtry-With-resources statement. In the examplewriteToFileZipFileContents, An exception can be thrown fromtryBlock, and up to two exceptions can be thrown fromtry-With-resources statement when it tries to closeZipFileAndBufferedWriterObjects. If an exception is thrown fromtryBlock and one or more exceptions are thrown fromtry-With-resources statement, then those exceptions thrown fromtry-With-resources statement are suppressed, and the exception thrown by the block is the one that is thrown bywriteToFileZipFileContentsMethod. You can retrieve these suppressed tions by callingThrowable.getSuppressedMethod from the exception thrown bytryBlock.

Classes That Implement the AutoCloseable or Closeable Interface

See the Javadoc ofAutoCloseableAndCloseableInterfaces for a list of classes that implement either of these interfaces.CloseableInterface extendsAutoCloseableInterface.closeMethod ofCloseableInterface throws exceptions of typeIOExceptionWhilecloseMethod ofAutoCloseableInterface throws exceptions of typeException. Consequently, subclasses ofAutoCloseableInterface can override this behavior ofcloseMethod to throw specialized exceptions, suchIOException, Or no exception at all.

 

 

 

Related Article

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.