Java Reference
In-Depth Information
throw new ReportCreationException(ioe);
}
Thisexampleassumesthatahelpermethodhasjustthrownageneric IOException
instance as the result of trying to create a report. The public method's contract states
that ReportCreationException isthrowninthiscase.Tosatisfythecontract,the
latter exception is thrown. To satisfy the developer who is responsible for debugging
a faulty application, the IOException instance is wrapped inside the Re-
portCreationException instance that is thrown to the public method's caller.
Sometimes, acatch blockmight notbeable tofullyhandle anexception. Perhapsit
needsaccesstoinformationprovidedbysomeancestormethodinthemethod-callstack.
However, the catch block might be able to partly handle the exception. In this case, it
shouldpartlyhandletheexception,andthenrethrowtheexceptionsothatahandlerin
theancestormethodcanfinishhandlingtheexception.Thisscenarioisdemonstratedin
the following example:
catch (FileNotFoundException fnfe)
{
// Provide code to partially handle the exception here.
throw fnfe; // Rethrow the exception here.
}
Final Rethrow
Java7'scompileranalyzesrethrownexceptionsmorepreciselythanitspredecessors,but
onlywhennoassignmentsaremadetotherethrownexception'scatchblockparameter
(the parameter is effectively final ). When an exception originates from the preced-
ingtryblockandisasupertype/subtypeoftheparameter'stype,thecompilerthrowsthe
actualtypeofthecaughtexceptioninsteadofthrowingthetypeoftheparameter(asis
done in previous Java versions).
Thepurposeofthis final rethrow featureistofacilitateaddingatrystatementaround
a block of code to intercept, process, and rethrow an exception without affecting the
staticallydeterminedsetofexceptionsthrownfromthecode.Also,thisfeatureletsyou
provideacommonexceptionhandlertopartlyhandletheexceptionclosetowhereit's
thrown, and provide more precise handlers elsewhere that handle the rethrown excep-
tion. Consider Listing 3-27 .
Listing 3-27. A pressure simulation
Search WWH ::




Custom Search