Thursday, June 21, 2007

Strive for exception safe code

When exceptions are thrown, foolowng should happen:

 Leak no resources ---use resource classes to manage all resources. Such classes also make code shorter.
Don't allow data structures to become corrupted---don't be left pointing to a deleted object,

Exception safe functions offer one of the following guarantees:
Basic guarantee --- exception thrown means program will remain in a valid state ( invariants satisfied etc)though exact state maybe unknown

Strong guarantee -- exception thrown means program state is unchanged. Calls to such functions are atomic…so boolean success or failure

NoThrow guarantee-- never throw exceptions. All operations on built in types are no throw.

Exception safe code always offers one of the three guarantees above. If not its not exception safe.

Int doSomething() throw() ---this doesn't mean no exc thrown, but that if a exception is thrown means serious error and call unexpected fun.

Try strongest guarantee but very hard.Strong guarantee is pretty hard because something could have changed state and you don't know what change it called

The general design strategy that you can use to get strong guarantee is copy , change copy  and swap in a non throwing oepration….obviously its costly and maynot give strong guarantee.

Normal : real obj = real obj { ptr to real data} --pimpl idiom

A functions exception safety guarantee is part of its interface….so give it as much weight as to other parts of its interface.

Things to remember:
Exception safe functions leak no resources and allow no data structures to become corrupted, even when exceptions are thjrown. Such functions offer the basic, strong on nothrow guarantees.

The strong guarantee can often be implemented via copy and swap, but the storng guarantee is not practical for all functions.

A function can usually offer a guarantee no stronger than the weakest guarantee of the functions it calls.


1 comment:

Unknown said...

Thank you! I found this article informative and useful. Anyways, while browsing through different websites to understand error handling, I landed up at this page which made me understand different concepts in error handling - http://mortoray.com/2013/12/05/is-exception-safe-code-truly-possible/