• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Junilu Lacar
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Piet Souris
  • Carey Brown
  • Stephan van Hulst
Bartenders:
  • Frits Walraven
  • fred rosenberger
  • salvin francis

Ensuring all resources are properly released

 
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Bartender
Posts: 9625
16
Mac OS X Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic