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 ();}}}