Try-with-resources statement

Source: Internet
Author: User
Tags readfile throwable

This section describes how to use the try statement to manage resources introduced in Java 7. This section is closely related to the exception handling described in the previous section. The new method addsuppressed in throwable described in the previous section is added for the try-with-resourcces statement. Most developers know the principle of who applies for and who releases resources. These resources involve primary storage, disk files, network connections, and database connections in the operating system. A limited number of entities that need to be applied for and released should be included in the scope of resource management.

When using resources, various exceptions may be thrown, such as various exceptions when reading disk files and accessing the database. One requirement of resource management is that the requested resources should be correctly released no matter whether the operation is successful or not. In the previous section, we have a typical example of resource release. Here we will talk about the enhancements to resource management in Java 7.The try statement is enhanced in Java 7 to support resource management to ensure that resources are always correctly released.. Example:

package test; import Java. io. bufferedreader; import Java. io. filereader; import Java. io. ioexception; public class resourcebasicusage {Public String readfile (string path) throws ioexception {try (bufferedreader reader = new bufferedreader (New filereader (PATH ))) {// note here stringbuilder builder = new stringbuilder (); string line = NULL; while (line = reader. readline ())! = NULL) {builder. append (line); builder. append (string. format ("% N");} return builder. tostring () ;}} public static void main (string [] ARGs) {resourcebasicusage usage = new resourcebasicusage (); try {system. out. println (usage. readfile ("F:/manifest_provider_loophole.txt");} catch (ioexception e) {e. printstacktrace () ;}}

The above Code does not need to use finally statements to ensure that the opened stream is properly closed, which is automatically completed. Compared with the traditional use of finally statements, this method is much simpler. Developers only need to care about the business logic of resources. Resource application is performed in the try clause, and resource release is completed automatically. When the try-with-resources statement is used, exceptions may occur in the try statement or when resources are released. If an exception occurs during Resource Initialization or in the try statement, and the release operation is normal, the exception in the try statement will be thrown. If there is an exception in both the try statement and the release resource, the final exception thrown is an exception in the try statement. The exception in the release of the resource will be added as a restrained exception, that is, throwable. the addsuppressed method.

Resources that can be managed by the try statement must meet one condition, that is, the Java class must be implemented.Java. Lang. autocloseable InterfaceOtherwise, a compilation error occurs. When resources need to be released, the close method of this interface is automatically called. Many interfaces or classes in the Java class library inherit or implement this interface so that they can be used in try statements. Among these existing common interfaces or classes, the most common interfaces are those related to I/O operations and databases. I/O-related Java. io. closeable inherits autocloseable, and Java related to the database. SQL. connection, Java. sqlresultset and Java. SQL. statement also inherits this interface. If you want your own classes to be able to use the try statement for Automatic Resource Management, you only need to implement the autocloseable interface.

In addition to managing a single resource,Try-with-resources can also manage multiple resources. Example:

package test; import Java. io. fileinputstream; import Java. io. fileoutputstream; import Java. io. ioexception; import Java. io. inputstream; import Java. io. outputstream; public class multipleresourcesusage {public void copyfile (string frompath, string topath) throws ioexception {try (inputstream input = new fileinputstream (frompath); // note, the semicolon outputstream output = new fileoutputstream (topath) {byte [] Bu is used here. Ffer = new byte [8192]; int Len =-1; while (LEN = input. Read (buffer ))! =-1) {output. write (buffer, 0, Len) ;}} public static void main (string [] ARGs) {multipleresourcesusage usage = new multipleresourcesusage (); try {usage. copyfile ("F:/manifest_provider_loophole.txt", "F:/aaa.txt");} catch (ioexception e) {e. printstacktrace () ;}}

When multiple resources are managed, exceptions may occur when each resource is released. All these exceptions will be added to the list of restrained exceptions thrown in Resource Initialization exceptions or try statement blocks.

The catch and finally clauses can also be used in the try-with-resource statement. The catch clause can capture the try statement block and various exceptions that may occur when resources are released.

Try-with-resources statement

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.