Information Technology Reference
In-Depth Information
community does not need to create its own strategies for exception safety;
the C++ community did all the hard work for us. Starting with Tom
Cargill's article “Exception Handling: A False Sense of Security,” and con-
tinuing with writings by Dave Abrahams, Herb Sutter, Scott Meyers, Matt
Austern, and Greg Colvin, the C++ community developed a series of best
practices that we can adapt to C# applications. The discussions on excep-
tion handling occurred over the course of six years, from 1994 to 2000.
They discussed, debated, and examined many twists on a difficult problem.
We s h o u l d l e v e r a g e a l l t h a t h a r d w o r k i n C # .
Dave Abrahams defined three exception-safe guarantees: the basic guar-
antee, the strong guarantee, and the no-throw guarantee. Herb Sutter dis-
cussed these guarantees in his book Exceptional C++ (Addison-Wesley,
2000). The basic guarantee states that no resources are leaked and all
objects are in a valid state after your exception leaves the function emitting
it. That means after any finally clauses have run in the method that
throws the exception. The strong exception guarantee builds on the basic
guarantee and adds that if an exception occurs, the program state did not
change. The no-throw guarantee states that an operation never fails, from
which it follows that a method does not ever throw exceptions. The strong
exception guarantee provides the best tradeoff between recovering from
exceptions and simplifying exception handling.
Yo u g e t s o m e h e l p o n t h e b a s i c g u a r a n t e e f r o m t h e . N E T C L R . T h e e n v i -
ronment handles memory management. The only way you can leak
resources due to exceptions is to throw an exception while you own a
resource that implements IDisposable. Item 15 explains how to avoid leak-
ing resources in the face of exceptions. But that's only part of the story.
Yo u a r e s t i l l r e s p o n s i b l e f o r e n s u r i n g t h a t y o u r o b j e c t ' s s t a t e i s v a l i d . S u p -
pose your type caches the size of a collection, along with the collection.
Yo u ' d n e e d t o e n s u r e t h a t t h e s i z e m a t c h e s t h e a c t u a l s t o r a g e a f t e r a n A d d ( )
operation threw an exception. There are countless actions your application
may have that if only partially completed would leave your application in
an invalid state. These cases are harder to handle, because there are fewer
standard idioms for automatic support. Many of these issues can be best
solved by adhering to the strong guarantee.
The strong guarantee states that if an operation terminates because of an
exception, program state remains unchanged. Either an operation com-
pletes or it does not modify program state; there is no middle ground. The
advantage of the strong guarantee is that you can more easily continue
 
Search WWH ::




Custom Search