Java Reference
In-Depth Information
copy() methodends(normallyorviaathrownexception), fis 'sand fos 's close()
methodsarecalled,butintheoppositeordertowhichtheseresourceswerecreated( fis
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.
Note Atry-with-resourcesstatementcanincludecatchandfinally.Theseblocksare
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
cannot fail.
Note Implementationsof Closeable 's close() methodare idempotent ;subse-
quentcallsto close() havenoeffectontheresource.Incontrast,implementationsof
AutoCloseable 's close() methodarenotrequiredtobeidempotent,butmaking
them idempotent is recommended.
Assertions
Writingsourcecodeisnotaneasytask.Alltoooften, bugs (defects)areintroducedinto
the code. When a bug is not discovered before compiling the source code, it makes it
intoruntimecode,whichwillprobablyfailunexpectedly.Atthispoint,thecauseoffail-
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
Search WWH ::




Custom Search