Content deleted Content added
→Stack management and heap management: Talking about stack and heap is too specific (think about Python's "with" statement); this concept is more general and applies to lexical scope versus explicit releasing of the resource |
→Basic techniques: Remove the "def work_with_file" lines which are not useful |
||
Line 37:
The basic approach to resource management is to acquire a resource, do something with it, then release it, yielding code of the form (illustrated with opening a file in Python):
<syntaxhighlight lang=python>
▲ ...
▲ f.close()
</syntaxhighlight>
This is correct if the intervening <code>...</code> code does not contain an early exit (<code>return</code>), the language does not have exceptions, and <code>open</code> is guaranteed to succeed. However, it causes a resource leak if there is a return or exception, and causes an incorrect release of unacquired resource if <code>open</code> can fail.
Line 48 ⟶ 47:
The resource leak can be resolved in languages that support a <code>finally</code> construction (like Python) by placing the body in a <code>try</code> clause, and the release in a <code>finally</code> clause:
<syntaxhighlight lang=python>
try:
finally:
...▼
</syntaxhighlight>
This ensures correct release even if there is a return within the body or an exception thrown. Further, note that the acquisition occurs ''before'' the <code>try</code> clause, ensuring that the <code>finally</code> clause is only executed if the <code>open</code> code succeeds (without throwing an exception), assuming that "no exception" means "success" (as is the case for <code>open</code> in Python). If resource acquisition can fail without throwing an exception, such as by returning a form of <code>null</code>, it must also be checked before release, such as:
<syntaxhighlight lang=python>
try:
finally:
</syntaxhighlight>
While this ensures correct resource management, it fails to provide adjacency or encapsulation. In many languages there are mechanisms that provide encapsulation, such as the <code>with</code> statement in Python:
<syntaxhighlight lang=python>
</syntaxhighlight>
|