Java Reference
In-Depth Information
Althoughamethod'sreturnvaluemustbeexaminedtoseeifitrepresentsanexcep-
tion,errorcodesarealltooeasytoignore.Forexample,alazydevelopermightignore
thereturncodefrom
Logger
's
connect()
methodandattempttocall
log()
.Ignor-
ingerrorcodesisonereasonwhyanewapproachtodealingwithexceptionshasbeen
invented.
Thisnewapproachisbasedonobjects.Whenanexceptionoccurs,anobjectrepres-
enting the exception is created by the code that was running when the exception oc-
curred. Details describing the exception's surrounding context are stored in the object.
These details are later examined to work around the exception.
Theobjectisthen
thrown
,orhandedofftotheJVMtosearchfora
handler
,codethat
canhandletheexception.(Iftheexceptionisanerror,theapplicationshouldnotprovide
ahandlerbecauseerrorsaresoserious[e.g.,theJVMhasrunoutofmemory]thatthere's
practicallynothingthatcanbedoneaboutthem.)Whenahandlerislocated,itscodeis
executed to provide a workaround. Otherwise, the JVM terminates the application.
Caution
Codethathandlesexceptionscanbeasourceofbugsbecauseit'softennot
thoroughly tested. Always make sure to test any code that handles exceptions.
Apartfrombeingtooeasytoignore,anerrorcode'sBooleanorintegervalueisless
meaningfulthananobjectname.Forexample,
fileNotFound
isself-explanatory,but
whatdoes
false
mean?Also,anobjectcancontaininformationaboutwhatledtothe
exception. These details can be helpful to a suitable workaround.
The Throwable Class Hierarchy
Javaprovidesahierarchyofclassesthatrepresentdifferentkindsofexceptions.These
classesarerootedin
java.lang.Throwable
,theultimatesuperclassforall
throw-
ables
(exception and error objects—exceptions and errors, for short—that can be
methods.