Database Reference
In-Depth Information
} finally {
try {
if( tempFileIS != null ) tempFileIS.close();
} catch( Exception y ){}
}
return returnString;
}
}
In
doWork()
we have a
try
block around the
open()
of the
FileInputStream
. If anything should
happen to cause an exception to be thrown, we will catch it in the next block. Then whether we have
caught an exception or not, we will enter the
finally
block and execute the
FileInputStream.close()
method.
You might have a couple questions. The first might be, “Why can't we close the
FiIeInputStream
in
both the t
ry
and in the
catch
blocks?” The answer is you
can
do that. However, repeating code is bad
practice, and you may have a problem with the
close()
in the
catch
block that will cause another
exception to be handled, thus compounding the troubleshooting effort.
A second question you may have is. “Why don't we just put the
FileInputStream.close()
outside both
the
try
and the
catch
, and skip the
finally
block?” That is a bad idea because sometimes you will both
catch an exception and throw it or another exception, like this:
} catch( IOException x ) {
throw new AppException( x.toString() );
}
FileInputStream.close();
If this were your code, and you caught an
IOException
, you would never reach the
FileInputStream.close()
line. The
throw
statement inside your
catch
, since it is not caught here, would
exit the current method, throwing an
AppException
to whatever code called this method.
Looking back up at our example, you will see this set of blocks within the
finally
block:
} finally {
try {
if( tempFileIS != null ) tempFileIS.close();
} catch( Exception y ){}
}
Closing the
FileInputStream
can throw an
IOException
, and we need to deal with it (catch it or
throw it). I choose to catch it and do nothing, at this point. I use this as my standard syntax for a
finally
block. Generally, we are just doing cleanup, and whatever work I might have been doing should have
been completed, or would have thrown an exception, which I've already handled.
If I can't clean this up (e.g., close the
FileInputStream
), then it is true I may need to fix something,
but if I've gotten this far, then I've already used the resource, in which case I should be able to close it. If
I failed to use it, then I've already handled a related exception,
and another exception here would be
superfluous. So I usually do nothing inside the
catch
block that I have inside my
finally
block.