I am using a buffered writer and my code, closes the writer in the finally block. My code is like this.
........... BufferedWriter theBufferedWriter = null; try{ theBufferedWriter =..... .... ...... ..... } catch (IOException anException) { .... } finally { try { theBufferedWriter.close(); } catch (IOException anException) { anException.printStackTrace(); } }
I have to use the try catch inside the clean up code in finally as theBufferedWriter might also throw an IOException. I do not want to throw this exception to the calling methos. Is it a good practice to use a try catch in finally? If not what is the alternative? Please suggest.
Regards, Hiral
it's ok, but to check null first is better.
I actually don't think there's anything inherently wrong about nested Try / Catch blocks, except that they can be difficult to navigate and are likely a sign that you could do some refactoring (the inner Try / Catch into its own method, for example).
A somewhat nicer way to do this is to use IOUtils.closeQuiety from Apache commons-io. It keeps your code tidy and eliminates some of the boilerplate that's inherent in Java.
You code then becomes:
BufferedWriter theBufferedWriter = null; try{ theBufferedWriter = ... ... } catch (IOException anException) { ... } finally { IOUtils.closeQuietly(theBufferedWriter); }
Much nicer and more expressive.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With