Re: IO pattern
On 12/10/2010 6:55 PM, 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.
Depends on what you want to do with the "unexpected" exception.
One possibility is to let it propagate:
void method() throws IOException {
InputStream stream;
try {
stream = ...;
do_stuff_with(stream);
} catch (EOFException ex) {
// Just as I expected!
} finally {
stream.close(); // or whatever
}
}
Another is to catch 'em both and give the caller a success/failure
indication:
boolean method() {
InputStream stream;
try {
stream = ...;
do_stuff_with(stream);
} catch (EOFException ex) {
// Just as I expected!
return true;
} catch (IOException ex) {
System.err.println("Oops! " + ex);
return false;
} finally {
stream.close(); // or whatever
// Might need another try/catch here for errors
// in close(), or else let *that* one propagate
// (if it happens) even though a "normal" error
// doesn't.
}
}
.... and there must be forty-'leven other possibilities. What's
wrong with the simple ones? (I'm not implying they're necessarily
right for all occasions, just asking why they don't meet your needs.)
--
Eric Sosman
esosman@ieee-dot-org.invalid