Re: Closing Files that Weren't Successfully Opened
Dagon wrote:
It's not uncommon to see code like:
finally {
if (someResource != null) {
try {
someResource.close();
} catch (exceptionsCloseCanThrow ecct) {
logger.error("WTF!", ecct);
}
}
}
This is ugly, and an admission that you haven't tracked the state of your
resource very well, but it does always make sure you've closed the resource if
possible.
Until the new resource-release idioms come on line, there's a certain ugliness
that's unavoidable.
I like the assign-once idioms, i.e., no initial assignment to 'null', and
therefore assertable non-nullity.
Something like:
public void useResource( String src, String dst )
{
final BufferedReader reader;
try
{
reader = new BufferedReader( new FileReader( src ));
}
catch ( IOException exc )
{
final String msg = "cannot open \"+ src +"\". "
+ exc.getLocalizedMessage();
logger.error( msg, exc );
throw new IllegalStateException( msg, exc );
}
assert reader != null;
final BufferedWriter writer;
try
{
writer = new BufferedWriter( new FileWriter( dst ));
}
catch ( IOException exc )
{
final String msg = "cannot open \"+ dst +"\". "
+ exc.getLocalizedMessage();
logger.error( msg, exc );
try
{
reader.close();
}
catch ( IOException cex )
{
final String cmsg = "cannot close \"+ src +"\". "
+ cex.getLocalizedMessage();
logger.error( cmsg, cex );
}
throw new IllegalStateException( msg, exc );
}
assert writer != null;
try
{
workWith( reader, writer ); // no closing inside that method
}
finally
{
try
{
reader.close();
}
catch ( IOException cex )
{
final String cmsg = "cannot close \"+ src +"\". "
+ cex.getLocalizedMessage();
logger.error( cmsg, cex );
}
try
{
writer.close();
}
catch ( IOException cex )
{
final String cmsg = "cannot close \"+ dst +"\". "
+ cex.getLocalizedMessage();
logger.error( cmsg, cex );
}
}
}
--
Lew
Honi soit qui mal y pense.