Database Reference
In-Depth Information
TRY/FINALLY TACK-ON DEBUGGING AND SYNCHRONIZATION
There is one case where I have found the need for a set of
try
and
finally
blocks, without a
catch
block.
If you have written a method and you need to temporarily add debugging to it without over-cluttering your
existing code, you can use a
try
and
finally
block pair to your advantage. Look at the following skeleton
of a method named
methodName()
:
returnType methodName() throws Exception {
try {
while() {
if() {
}
}
for() {
}
catch( Exception x ) {
} finally {
}
}
To do temporary spot debugging on this method, we could declare a file output before the
try
block, then
write debug messages to it throughout the method. For completeness, security and good practice, we
would then
flush()
the file and
close()
it in the existing
finally
block. The only problem with that is
that we have cluttered up our code, and making those changes and then cleaning it up later (removing the
debugging) gives an abundance of opportunity to introduce more errors. In brief, that approach would yield
code that appears more like permanent debugging code, like this:
returnType methodName() throws Exception {
PrintStream debugOut = null;
try {
debugOut = new PrintStream ( new FileOutputStream( “debug.txt” ) );
while() {
debugOut.println( “message 1” );
if() {
}
}
for() {
}
catch( Exception x ) {
} finally {
if( debugOut != null ) {
debugOut.flush();
debugOut.close();
}
}
}