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.
with and c# has
using to help make resource cleanup easier, but let's disregard those features for a minute. Given that:
- It's a programming error not to explicitly close open files.
- 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')) #k.f.close()
Two problems: It requires wrappers, Python doesn't like to throw exceptions from destructors.
(Read this https://stackoverflow.com/questions/2807241/what-does-the-expression-fail-early-mean-and-when-would-you-want-to-do-so SO question for background on why failing fast is often desirable)