Database Reference
In-Depth Information
We can reduce the potential for introducing errors with a simpler
try
/
finally
block pair. If we are seeing
problems that we know are happening in the
while
block in our example method, then we can surround
just that block with our troubleshooting. (Be aware that you cannot break existing blocks by putting a new
code block around just the open or close of an existing block.) Our solution might look like the following
(the code in bold has been added):
returnType methodName() throws Exception {
try {
// temp code
PrintStream debugOut = null;
try {
debugOut = new PrintStream ( new FileOutputStream( “debug.txt” ) );
// to here
while() {
debugOut.println( “message 1” );
if() {
debugOut.println( “message 2” );
}
debugOut.println( “message 3” );
}
// temp code
debugOut.println( “message 4” );
} finally {
if( debugOut != null ) {
debugOut.flush();
debugOut.close();
}
}
// to here
for() {
}
catch( Exception x ) {
} finally {
}
}
We have successfully added spot debugging, right where needed, and we have used good coding practice
by closing our file output in a
finally
block. Note that if our method is not already catching or throwing an
IOException
, we will need a new
catch
block before our new
finally
block, and we will need a set of
try
/
catch
blocks within our added
finally
block, around the
flush()
and
close()
. Cleaning this up
(removing the debugging) only requires removing the opening and closing sections of code (our new
try
and
finally
declarations and the surrounding code we added) and removing each of the
debugOut.println()
statements.