Re: (File)OutputStreams and their usage
Leonard Milcin wrote:
public void load(File file) throws ... {
OutputStream os;
try {
os = new FileOutputStream(file);
load(os);
} finally {
if (os!=null) {
os.close();
}
}
}
That looks much cleaner. The caller has to deal with all those checked
excetions, though. You can convert to another type of exception (like
unchecked exception).
The check for os non-nullity is not needed here. Because of that, you can
move the close() inside the try{} block. This helps, too, because close() can
throw an Exception, too.
The idiom above is a bit too loose. It doesn't log, it doesn't translate the
Exception into the application domain, and it allows Exceptions to happen in
the finally{} block. It also doesn't admit of a coherent Exception-handling
strategy throughout the application.
Catch-log-and-rethrow is a better idiom, or declare a return type that can
indicate failure if client code cares not for the reason.
Catch-log-and-rethrow puts the condition into application-specific terms. One
would create an application-specific Exception subtype, or a hierarchy of them.
try
{
OutputStream os = new FileOutputStream(file);
workWithGuaranteedNonNullValue( os );
// factored method that handles its own exceptions
os.close();
}
catch ( IOException exc )
{
logger.error( IOERROR_MSG, exc );
}
It is easy to add a return value, with success from the try{} or failure from
the catch{}.
--
Lew