This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Ensuring all resources are properly released

 
Garrett Rowe
Ranch Hand
Posts: 1296
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The textbook that I began my Java learning with preached against try/catch/finally blocks.



In favor of either a try/catch or a try/finally or some nesting thereof
And for the little bits of code I have written this has served me well. However I was looking at this Java Anti-Patterns site, and although I didn't agree with everything the author wrote, one thing that caught my eye was this section on Incomplete Exception Handlling It made me wonder if I am possibly opening myself up to a slight memory leak by not releasing all my resources properly.
If an exception is thrown while closing the InputStream, the OutputStream never gets closed. Is there some elegant solution to this other than the author's suggestion to wrap the close() calls in a try/catch which seems like it would tremendously clutter the code.

Edit: Although that does seem to solve the problem of *losing* the original Exception as its been hidden by the Exception thrown while closing the streams.
[ July 31, 2006: Message edited by: Garrett Rowe ]
 
Joe Ess
Bartender
Posts: 9214
9
Linux Mac OS X Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've seen bad exception handling in the form of database queries bring down enterprise servers. While that last "finally" construct is ugly, it is the proper way to handle it. Some people create a "close" method which handles the close exception silently and invoke that from the "finally" block. Put it in a utility class and use it for every stream/reader.
Apache IO Commons provides a class that does the same, so you don't have to reinvent the wheel.
Personally, I just make my "finally" blocks the ugly way.
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic