copy() methodends(normallyorviaathrownexception), fis 'sand fos 's close()
was created before fos ). Hence, fos.close() is called before fis.close() .
Supposethat fos.write(buffer, 0, n) throwsan IOException instance.
Now suppose that the behind-the-scenes fos.close() method call results in a
thrown IOException instance.Thislatterexceptionissuppressed,andtheexception
thrownby fos.write(buffer, 0, n) istheexceptionthrownoutofthe copy()
method.Thesuppressedexceptioncanberetrievedbycalling Throwable 's Throw-
able getSuppressed() method, which I previously presented.
executed after all declared resources have been closed.
To take advantage of try-with-resources with your own classes, keep in mind that
a resource class must implement the java.lang.AutoCloseable interface or its
java.lang.Closeable subinterface.Eachinterfaceprovidesa close() method
that performs the close operation.
Unlike Closeable 's close() method, which is declared to throw only IOEx-
ception (orasubtype), AutoCloseable 's close() methodisdeclaredtothrow
Exception .Asaresult,classesthatimplement AutoCloseable , Closeable ,or
asubinterfacecandeclaretheir close() methodstothrowanykindofexception.The
close() method should be declared to throw a more specific exception, or (as with
java.util.Scanner 's close() method)tonotthrowanexceptionifthemethod
Note Implementationsof Closeable 's close() methodare idempotent ;subse-
quentcallsto close() havenoeffectontheresource.Incontrast,implementationsof
AutoCloseable 's close() methodarenotrequiredtobeidempotent,butmaking
them idempotent is recommended.
Writingsourcecodeisnotaneasytask.Alltoooften, bugs (defects)areintroducedinto
the code. When a bug is not discovered before compiling the source code, it makes it
ure can be very difficult to determine.
Developers often make assumptions about application correctness, and some deve-
lopers think that specifying comments that state their beliefs about what they think is