Given these class definitions:
class ReadDevice implements AutoCloseable { public void read() throws Exception { System.out.print("read; "); throw new Exception(); }/*w w w .j av a 2 s .c o m*/ public void close() throws Exception { System.out.print("closing ReadDevice; "); } } class WriteDevice implements AutoCloseable { public void write() { System.out.print("write; "); } public void close() throws Exception { System.out.print("closing WriteDevice; "); } }
What will this code segment print?
try(ReadDevice rd = new ReadDevice(); WriteDevice wd = new WriteDevice()) { rd.read(); wd.write(); } catch(Exception e) { System.out.print("Caught exception; "); }
a) read; closing WriteDevice; closing ReadDevice; Caught exception; b) read; write; closing WriteDevice; closing ReadDevice; Caught exception; c) read; write; closing ReadDevice; closing WriteDevice; Caught exception; d) read; write; Caught exception; closing ReadDevice; closing WriteDevice; e) read; Caught exception; closing ReadDevice; closing WriteDevice;
a)
the read()
method of ReadDevice
throws an exception, and hence the write()
method of WriteDevice
is not called.
the try-with-resources statement releases the resources in the reverse order from which they were acquired.
hence, the close()
for WriteDevice
is called first, followed by the call to the close()
method for ReadDevice
.
Finally, the catch block prints "Caught exception;" to the console.