Reputation: 2967
This question is inspired by this post: reason for memory leakage in C C++
What are the other kind for problem that can arise because of using exceptions?
I mean what are the problems that we should keep in mind while using exception handling
Upvotes: 2
Views: 1120
Reputation: 20039
Bjarne Stroustrup has made the chapter on exception safety (The C++ Programming Language, 3rd ed.) available.
Additionally you have to make sure that exceptions interrupting your functions mid-call will be harmless. If you use RAII (the generally recommended approach) to automatically release mutexes, for instance, you could get halfway through an atomic operation (money withdrawn from bank account 1), throw an exception, and leave the system in an inappropriate state (money not yet deposited to bank account 2).
The somewhat classic ScopeGuard article has additional information.
Upvotes: 2
Reputation: 106096
Firstly, the memory leakage question you link to isn't related to exception handling per se, it's simply a matter of not handling all the ways in which some code you want to run may be bypassed. It would be equally applicable for return
, exit()
, a break
or if
that bypassed some cleanup code etc. - it's just less obvious with exceptions. RAII is the normal way to handle this class of error (though exit()
prevents some objects' destructors running).
Re exceptions:
f(shared_ptr<int>(new int(2)), g());
, where g() may throw, may leak memoryUpvotes: 0
Reputation: 170499
Actually any algorithm can break if an unanticipated exception is thrown.
For example, the algorithms needs to perform two actions sequentially and the second action results in an exception - the first one is not cancelled (unless you take care of this) and the program is in inconsistent state now. In the situation you linked to the inconsistency manifests itself as a memory leak - code intended to deallocate memory but the deallocation code wasn't run because of an exception.
The solution is to expect exceptions and use RAII for managing resources and states consistency. For example if you need to perform two actions you first create a "bracket class" instance on stack and after the second action is done you run a special method on that instance that means that both actions have run successfully. If an exception is thrown the destructor of that class will rollback the first action.
Upvotes: 4