Re: IO pattern
On 12/11/2010 08:43 AM, Screamin' Lord Byron wrote:
On 11. 12. 10. 12:55 AM, Roedy Green wrote:
Let's say you want to read a sequential file with code that will throw
an EOFException on end of file and an IOException if there is some
problem opening, reading or closing the file.
What try block structure do you use to declare the InputStream, loop
to read, and handle closing the file? I just wondered if there is
some slick terse way of doing it I have not thought of. I have nested
try blocks.
I find nested try blocks quite nice and easy to read.
try {
...
InputStream iStream =
new FileInputStream("somefile"); // we are able catch this
try {
while (...) {
... = iStream.read(); // and this
}
} finally {
iStream.close(); // and this
}
} catch (EOFException ex) {
// we're done
...
} catch (IOException ex) {
// something went terribly wrong
...
} ... // catch others, perhaps SecurityException that FileInputStream
// threatens to throw
What's wrong with it?
You're catching 'EOFException' for a 'close()' call; that doesn't make sense.
It doesn't give as fine-grained control as separately catching the 'close()'
exception. The nesting and the use of traditional '{' placement obscure
readability.
In the special case of resource release, e.g., 'iStream.close()', I often use
a simple wrapper method:
private void close( InputStream str )
{
try
{
str.close();
}
catch( IOException exc )
{
final String msg = "Failure to close";
logger.error( msg, exc );
}
}
Or such ...
--
Lew