Content deleted Content added
Rephrase paragraph about Python "with" statement, change plain link to reference |
→Motivation: elab, narrowly about exceptions |
||
Line 5:
Many garbage-collected languages offer language constructs to avoid having to call the dispose method explicitly in many situations. These language constructs leads to results similar to what is obtained with the [[Resource Acquisition Is Initialization]] (RAII) idiom in languages with deterministic memory management (e.g. [[C++]]).
==
It is very common to write code similar to the listing below when using resources that might throw exceptions in garbage-collected languages:
<source lang="csharp">
// Attempt to acquire the resource.
Resource resource = null;▼
// May fail, in which case throws exception and the try...finally statement is not executed.
try {
//
▲ resource = getResource();
// Perform actions with the resource.
...
} finally {
// Release resource, even if an exception is thrown.
// Resource might not have been acquired, or already freed▼
resource.dispose();▼
}
</source>
Line 26:
One disadvantage of this approach is that it requires the programmer to explicitly add cleanup code in a <code>finally</code> block. This leads to code size bloat, and failure to do so will lead to resource leakage in the program.
In more complex situations, one or several resource may be acquired, in some combination, and correctly releasing resources in all cases can be very verbose. For example, because the dispose method may itself throw an exception, the <code>try...finally</code> statements must in principle be nested.
<source lang="csharp">
▲Resource resource = null;
Resource resource2 = null;
try {
if (condition) {
// Attempt to acquire the resource.
resource = getResource();
}
try {
resource2 = getResource();
// Perform actions with the resources.
...
} finally {
// Resource might not have been acquired, or already freed
if (resource2 != null)
resource2.dispose();
}
} finally {
▲ // Resource might not have been acquired, or already freed
if (resource != null)
▲ resource.dispose();
}
</source>
== Language constructs ==
|