Dispose pattern: Difference between revisions

Content deleted Content added
Notes: init
Exceptions: elaborate with simple problems
Line 44:
Thus by not coupling resource management to object lifetime, the dispose pattern allows ''resources'' to be released promptly, while giving implementation flexibility for memory management. The cost of this is that resources must be managed manually, which can be tedious and error-prone.
 
== ExceptionsEarly exit ==
A key problem with the dispose pattern is that if the <code>dispose</code> method is not called, the resource is leaked. A common cause of this is early exit from a function, due to an early return or exception.
 
For example:
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="python">
def func(filename):
f = open(filename)
if a: return x
f.close()
return y
</source>
If the function returns at the first return, the file is never closed and the resource is leaked.
 
<source lang="python">
def func(filename):
f = open(filename)
g(f) # Do something with f that may raise an exception.
f.close()
</source>
If the intervening code raises an exception, the function exits early and the file is never closed, so the resource is leaked.
 
Both of these can be handled by a <code>try...finally</code> construct, which ensures that the finally clause is always executed on exit:
<source lang="python">
def func(filename):
try:
f = open(filename)
# Do something.
finally:
f.close()
</source>
 
More generically:
<source lang="csharp">
Resource resource = getResource();