Java Reference
In-Depth Information
throw new SubException1();
}
catch (SuperException se)
{
try
{
throw se;
}
catch (SubException2 se2)
{
}
}
}
}
Listing 3-28 compiles under Java 6 and earlier. However, it fails to compile under
Java 7, whose compiler detects and reports the fact that SubException2 is ever
thrown in the body of the corresponding try statement.
Althoughunlikelytooccur,it'spossibletorunintothisproblem.Insteadofgrumbling
aboutthebreakage,considerthevalueinhavingthecompilerdetectasourceofredund-
ant code whose removal results in cleaner source code and a smaller classfile.
Performing Cleanup
Insomesituations,youmightwanttopreventanexceptionfrombeingthrownoutofa
methodbeforethemethod'scleanupcodeisexecuted.Forexample,youmightwantto
close a file that was opened, but could not be written, possibly because of insufficient
disk space. Java provides the finally block for this situation.
The finally block consists of reserved word finally followed by a body, which
provides the cleanup code. A finally block follows either a catch block or a try block.
Intheformercase,theexceptionishandled(andpossiblyrethrown)beforefinallyex-
ecutes. In the latter case, finally executes before the exception is thrown and handled.
Listing 3-29 demonstrates the finally block in the context of a file-copying applica-
tion.
Listing 3-29. Cleaning up after handling a thrown exception
 
Search WWH ::




Custom Search