One of the things that always bugs me about using Readers and Streams in Java is that the close() method can throw an exception. Since it’s a good idea to put the close method in a finally block, that necessitates a bit of an awkward situation. I usually use this construction:
FileReader fr = new FileReader('SomeFile.txt'); try { try { fr.read(); } finally { fr.close(); } } catch(Exception e) { // Do exception handling }
But I’ve also seen this construction:
FileReader fr = new FileReader('SomeFile.txt'); try { fr.read() } catch (Exception e) { // Do exception handling } finally { try { fr.close(); } catch (Exception e) { // Do exception handling } }
I prefer the first construction because there’s only one catch block and it just seems more elegant. Is there a reason to actually prefer the second or an alternate construction?
UPDATE: Would it make a difference if I pointed out that both read and close only throw IOExceptions? So it seems likely to me that, if read fails, close will fail for the same reason.
I would always go for the first example.
If close were to throw an exception (in practice that will never happen for a FileReader), wouldn’t the standard way of handling that be to throw an exception appropriate to the caller? The close exception almost certainly trumps any problem you had using the resource. The second method is probably more appropriate if your idea of exception handling is to call System.err.println.
There is an issue of how far exceptions should be thrown. ThreadDeath should always be rethrown, but any exception within finally would stop that. Similarly Error should throw further than RuntimeException and RuntimeException further than checked exceptions. If you really wanted to you could write code to follow these rules, and then abstract it with the ‘execute around’ idiom.