Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it okay to use try catch inside finally?

Tags:

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

like image 212
Hiral Lakdavala Avatar asked Jun 16 '10 07:06

Hiral Lakdavala


People also ask

Can I use try catch inside finally?

it's ok, but to check null first is better.

Are nested try catches bad?

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).


1 Answers

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.

like image 178
Edward Dale Avatar answered Sep 22 '22 19:09

Edward Dale