Java7 New Grammar-try-with-resources

Source: Internet
Author: User
Tags throwable java se

Http://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html

The Try-with-resources Statement

The try -with-resources statement is a try statement this declares one or more resources. A Resource is as an object that must was closed after the program was finished with it. The try -with-resources statement ensures the resource is closed at the end of the statement. Any object is implements java.lang.AutoCloseable , which includes all objects which implement java.io.Closeable and can be used as a resource.

The following example reads the first line from a file. It uses an instance of BufferedReader -read data from the file. Was a resource that must being closed after the program is BufferedReader fini Shed with it:

With Try-with-resources, you can automatically turn off resources that implement the autocloseable or Closeable interface. For example, the following function automatically calls the Close method of Bufferdreader after the try statement finishes, regardless of whether the code it includes is performed properly or an exception occurs.

static string Readfirstlinefromfile (string path) throws IOException {  try (bufferedreader br = new BufferedReader (New FileReader (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'll 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, your can use a finally block to ensure that a resource is closed regardless of whether the try Statemen T completes normally or abruptly. The following example uses a finally block instead of a try -with-resources statement:

You can use the FINALLY clause to ensure that resources are closed before the try-with-resources occurs, such as the following method.
But one difference is that, in the Readfirstlinefromfilewithfinallyblock method, if an exception is thrown in the finally clause, the exception thrown in the try code block is suppressed.
Conversely, in the Readfirstlinefromfile method, if an exception is thrown in the close method of the open resource in the Try-with-resources statement and in the try code block, the exception thrown by the Close method is suppressed and the exception in the try code block is thrown.
In this regard, the last example can be seen.

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 is thrown from both the  tr Y  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 a block is suppressed. In the Java SE 7 and later, you can retrieve suppressed exceptions; See the section suppressed exceptions for more information.

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 and zipFileName creates a text file that contain s the names of these files:

You can declare multiple resources in a try-with-resources statement, which are closed in the reverse order of the declarations, such as the following method.

 public static void Writetofilezipfilecontents (String zipfilename, String outputfilename) throws Java.io.IOExcept    Ion {Java.nio.charset.Charset charset = java.nio.charset.Charset.forName ("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))  {//Enu Merate 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 and the declarations that is separated by a semicolon: and ZipFile BufferedWriter. When the block of code is directly follows it terminates, either normally or because of an exception, the close methods Of the BufferedWriter and ZipFile objects is automatically called in this order. Note that the close methods of resources is 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, SAL ES, 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 used in this example are part of the java.sql.Statement JDBC 4.1 and later API.

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

Note: A try-with-resources statement can also have catch and finally clauses. The catch and finally clauses are called after the resource opened in the Try-with-resources clause is closed.

Suppressed Exceptions

An exception can is thrown from the block of code associated with thetry-with-resources statement. In the examplewriteToFileZipFileContents, an exception can is thrown from thetryblock, and up to both exceptions can thrown from thetry-with-resources statement when it tries to close theZipFileandBufferedWriterObjects. If an exception are thrown from thetryBlock and one or more exceptions is thrown from thetry-with-resources statement, then those exceptions thrown from thetry-with-resources statement was suppressed, and the exception thrown by the block is the the one that's thrown by thewriteToFileZipFileContentsMethod. You can retrieve these suppressed exceptions by calling theThrowable.getSuppressedMethod from the exception thrown by thetryBlock.

Note: As mentioned earlier, if an exception is thrown in the close method of the open resource in the Try-with-resources statement and in the try code block, the exception thrown by the Close method is suppressed and the exception in the try code block is thrown.
After Java7, the suppressed exception can be obtained using the Throwable.getsuppressed method.

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 while the method of the IOException close AutoCloseable interface Throw s exceptions of type Exception . Consequently, subclasses of the AutoCloseable interface can override this behavior of the close method to throw specialized EXCEP tions, such as IOException , or no exception at all.

Example

[Java]View PlainCopy
  1. Import java.io.Closeable;
  2. Import java.io.IOException;
  3. Public class Dummyclosable implements Closeable {
  4. Private Final Boolean throwinclose;
  5. Private final String name;
  6. Public dummyclosable (boolean throwinconstruction, boolean throwinclose, String name) throws IOException {
  7. this.throwinclose = throwinclose;
  8. this.name = name;
  9. if (throwinconstruction) {
  10. throw New IOException ("throwing in construction");
  11. }
  12. }
  13. @Override
  14. public Void Close () throws IOException {
  15. if (throwinclose) {
  16. throw New IOException ("throwing in close");
  17. }
  18. SYSTEM.OUT.PRINTLN (name + "is closing ...");
  19. }
  20. public static void Main (string[] args) {
  21. try (dummyclosable d1 = new Dummyclosable (false, false, "a");
  22. Dummyclosable D2 = new Dummyclosable (true, false, "B");) {  
  23. throw New IOException ("in Main1");
  24. } catch (Exception ex) {
  25. Ex.printstacktrace (System.out);
  26. }
  27. System.out.println ("----end1----");
  28. try (dummyclosable d1 = new Dummyclosable (false, false, "a");
  29. Dummyclosable D2 = new Dummyclosable (false, true, "B");) {  
  30. throw New IOException ("in Main2");
  31. } catch (Exception ex) {
  32. Ex.printstacktrace (System.out);
  33. }
  34. System.out.println ("----end2----");
  35. }
  36. }

Running the above example, the results are as follows: [Plain]View PlainCopy
  1. A is closing ...
  2. Java.io.IOException:throwing in construction
  3. At Learning.io.dummyclosable.<init> (dummyclosable.java:14)
  4. At Learning.io.DummyClosable.main (dummyclosable.java:28)
  5. ----END1----
  6. A is closing ...
  7. Java.io.IOException:in main2
  8. At Learning.io.DummyClosable.main (dummyclosable.java:37)
  9. Suppressed:java.io.IOException:throwing in close
  10. At Learning.io.DummyClosable.close (dummyclosable.java:21)
  11. At Learning.io.DummyClosable.main (dummyclosable.java:38)
  12. ----END2----

http://blog.csdn.net/fw0124/article/details/49946975

Java7 New Grammar-try-with-resources

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.