What is the benefit to limiting throws allowed by a C++ function? [closed]

旧街凉风 提交于 2019-12-09 08:58:58

问题


What is the benefit of declaring the possible exception-throws from a C++ function? In other words, what does adding the keyword throw() actually do?

I've read that a function declaration such as void do_something() throw(); should guarantee that no exceptions originate from the do_something() function; however, this doesn't seem to hold true of functions called within do_something(), thus making it a weak guarantee.

Please outline the usefulness (and best-use cases) of this language feature.


回答1:


No one explains this better than Sutter

http://www.ddj.com/architect/184401544

The short version is

  1. Never write an exception specification
  2. Except possibly an empty one



回答2:


The C++ standard requires that the unexpected() function is called if a function attempts to throw an exception that is not on its exception list. A short description of this from MSDN is here: http://msdn.microsoft.com/en-us/library/awbt5tew(VS.80).aspx

Most compilers do not actually support this C++ feature.




回答3:


void do_something() throw(); 

This is a guarantee from the implementer's side that the function will never throw an exception. That is what a client of the function can expect. However, it also means any exception generated somewhere inside the function is handled and not rethrown back to the parent of do_something(). Shame on he who re-throw-eth from within, for there is nothing that'll stop him from throwing. This is because, throwing from within a function with an empty exception-specification is equivalent to throwing an exception not mentioned in the specification and making the std::unexpected() is to be expected followed by program termination.

BTW: The generally accepted definition of strong exception guarantee is: If a public operation fails for some reason, an exception is thrown, and the object's state is left unchanged (atomic operation).




回答4:


Basically, by declaring the function with throw(); you tell the compiler that you are one hundred per cent certain that the function is not going to throw any exceptions, allowing the compiler to perform some optimizations. If your function throws an exception anyway, you're in trouble, since it most likely results in undefined behavior.



来源:https://stackoverflow.com/questions/609332/what-is-the-benefit-to-limiting-throws-allowed-by-a-c-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!