1.3.4 try-with-resources (TWR), trywithresources

Source: Internet
Author: User

1.3.4 try-with-resources (TWR), trywithresources

The basic idea is to limit the scope of resources (such as files or similar things) to a code block. When the program leaves the code block, the resources will be automatically closed;

Ensure that try-with-resources takes effect. The correct usage is to declare independent variables for each resource;

Currently, the TWR feature relies on a newly defined interface to implement AutoCloseable. All the resource classes in the try clause of TWR must implement this interface. (Not all resource-related classes use this new technology; JDBC4.1 already has this feature ;)

Import java. io. fileInputStream; import java. io. IOException; import java. io. inputStream; import java. io. objectInputStream; public class CoinTWR {@ SuppressWarnings ("null") public static void main (String [] args) throws IOException {// throw an exception/** Resource Management **/try (FileInputStream fin = new FileInputStream ("someFile. bin "); ObjectInputStream in = new ObjectInputStream (fin )){//...} /** improved the error tracking capability (note the NullPointerException (NPE). * Ran As Java Application: * Exception in thread "main" java. lang. nullPointerException * at cointest. coinTWR. main (CoinTWR. java: 21) */try (InputStream I = null) {I. available ();}}}


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.