aspose file tools*
The moose likes I/O and Streams and the fly likes Ensuring all resources are properly released Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "Ensuring all resources are properly released" Watch "Ensuring all resources are properly released" New topic
Author

Ensuring all resources are properly released

Garrett Rowe
Ranch Hand

Joined: Jan 17, 2006
Posts: 1296
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 ]

Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
Joe Ess
Bartender

Joined: Oct 29, 2001
Posts: 8867
    
    8

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.


"blabbing like a narcissistic fool with a superiority complex" ~ N.A.
[How To Ask Questions On JavaRanch]
 
Consider Paul's rocket mass heater.
 
subject: Ensuring all resources are properly released