How should i place cleanup code in a finally block to close a file?
#1
I’m trying to understand how to properly use a finally block in my exception handling. I have a piece of code that opens a file connection, and I want to ensure the connection closes whether an exception occurs or not, but I’m not sure if I’m placing my cleanup logic correctly.
Reply
#2
Yeah I used a finally block once. I opened the file, did the work, and closed the handle in that block.
Reply
#3
I tried that approach, but in practice I still ran into cases where the close failed because something happened while tearing down, and it felt like chasing a ghost.
Reply
#4
Are you sure the cleanup is the real problem, or is the earlier code path holding the resource longer than it should?
Reply
#5
Sometimes I forget to check the resource state before closing, and I end up calling close twice. It taught me to add a guard, but it’s still rough.
Reply


[-]
Quick Reply
Message
Type your reply to this message here.

Image Verification
Please enter the text contained within the image into the text box below it. This process is used to prevent automated spam bots.
Image Verification
(case insensitive)

Forum Jump: