Added the Try-with-resource exception declaration
in JDK7, you can use Try-with-resource to implement exception handling and resource shutdown as long as the class or interface that implements the Autocloseable or Closeable interface is implemented
Exception throw order. In the Java SE 7 try-with-resource mechanism, exceptions are thrown in a different order from previous versions of Java SE 7.
is a resource that is declared first and then closed
JDK7 Previously, if Rd.readline () and Rd.close () (in the Finally block) throw an exception, only the exception in the finally block is thrown, and the exception in the Rd.readline () is not thrown. This often results in the resulting exception information that is not intended by the calling program.
If the try-with-resource mechanism is used in the JDK7 and later versions, if it throws an exception in the Try-with-resource declaration (either the file cannot be hit or the file cannot be closed) and rd.readline (); The Rd.readline () exception is only potential.
public class main { //when declaring a resource, it is necessary to analyze the closing order of resources, and then to declare the closed //can have catch and finally blocks in Try-with-resource. //only catch and finally blocks are executed after the Try-with-resource has been processed. public static void main (String[] args) { try (resource res = new resource (); resourceother resother = new Resourceother ();) { res.dosome (); resother.dosome (); } catch (Exception ex) { ex.printstacktrace (); } } // JDK1.7 the previous version, release the Resource static string readfirstlingfromfile (String path) throws ioexception { bufferedreader br = null; try { Br = new bufferedreader (New filereader (path)); return br.readline (); } catch (ioexception e) { e.prinTstacktrace (); } finally { if (br != null) br.close (); } return null; } //jdk1.7, using the Autocloseable interface //code more concise, fully static string readfirstlinefromfile (String path) throws ioexception { try (Bufferedreader br = new bufferedreader (new FileReader (path)) { return br.readline (); } }}class resource implements autocloseable { void dosome () { system.out.println ("Do something "); } @Override public void close () throws exception { system.out.println ("resource closed"); }}class resourceother implements Autocloseable { void dosome () { system.out.println ("do something Other "); } @Override &nbsP;public void close () throws exception { system.out.println ("other Resource closed "); }}
New auto-Release resource interface in JDK1.7 autocloseable