开发者

Problems that can arise with Exception-handling

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 mi开发者_运维知识库nd while using exception handling


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.


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.


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:

  • they can be left uncaught, resulting in program termination
  • they can be caught in the wrong place, resulting in inappropriate handling and possible unintended behaviour
  • classic boost::shared_ptr<> mistake: f(shared_ptr<int>(new int(2)), g());, where g() may throw, may leak memory
  • exception specifications are generally discredited
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜