Description
Deterministic destruction
Deterministic destruction is a guarantee that some specified resources will be released when exiting from the enclosing block even if we exit from the block by the means of exceptions.
Example
In python deterministic destruction is done using the with
statement.
with open("myfile","w") as f:
f.write("Hello")
Considering the code above we don't have to worry about closing a file explicitly. After the with
block, the file will be closed. Even when something throws an exception inside the with
block, the resources handled by the with
statement will be released (in this case closed).
Other languages
- C++ always had guaranteed destructor calls at scope exit for stack objects - even in the face of exceptions (see RAII).
- In C# there is the
using
statement for this same purpose. - Java has try-with-resources since Java7.
Julia?
It is my firm belief that Julia also needs to have a feature supporting deterministic destruction. We have countless cases when a resource needs to be closed at soon as possible: serial ports, database connections, some external api handles, files, etc. In cases like these deterministic destruction would mean cleaner code, no explicit close()
/ release()
calls and no sandwiching the code in try
.. catch
.. finally
blocks.