Stack Exchange Network

Stack Exchange network consists of 175 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Visit Stack Exchange
3 of 4 added 427 characters in body; edited tags

What if any languages treat undisposed resources as an error?

I've seen lots of code like the following example. It's in Python, but the same mistake is made in all languages with managed resources:

f = open('foo.txt', 'rb')
for line in f: print line

That's it. The error is that close(f) wasn't called so the file handle is kept open until some indeterministic time in the future when the runtimes memory management decides to reclaim memory.

Python has with and c# has using to help make resource cleanup easier, but let's disregard those features for a minute. Given that:

  1. It's a programming error not to explicitly close open files.
  2. The runtime can detect that an open file has not been closed.

Why then doesn't the runtime throw an error instead of being "helpful" and closing the file for the programmer? That would be the fail fast and fail early strategy. Is there a technical reason why it can't? Is there any languages that does it? Has the idea been considered before (I've googled but not found anything)?

Here is how you almost implement the feature in Python:

class mustclose:
    def __init__(self, f):
        self.f = f
    def __del__(self):
        if not self.f.closed:
            raise Exception("You forgot to close() me!")
k = mustclose(open('foo.txt', 'wb'))

Two problems: It requires wrappers, Python doesn't like to throw exceptions from destructors.

(Read this SO question for background on why failing fast is often desirable)