Can anyone explain C++ exception specifications to me?

前端 未结 5 1449
野趣味
野趣味 2021-02-07 21:24

Can anyone explain Exception Specifications as used in C++ ?

  • When are they used (I have rarely seen it used in code)
  • What are the pros and cons (benefits/
5条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-07 22:10

    They indicate to the programmer which exceptions will be thrown from that function. They have the advantage that you have the guarantee that no other exceptions can be thrown from that function. However, there is no compile-time checking of whether the function actually throws any exceptions other than what is indicated in the throw specifier. Instead, it's checked at runtime. And if it fails, then unexpected() is called, which by default calls abort() which in turn by default terminates your program. So, unless you really want your program to die if you screw up and an unexpected exception gets thrown, it's probably a bad idea to use them.

    The one place where I would actually recommend using them is on destructors. It's really bad if a destructor throws. They should never throw. So, if you use throw() on a destructor to indicate that it can't throw an exception, then you know that your program will die rather than continue in the bad state that it would be in after an exception was thrown from a destructor.

    Regardless, if you use any kind of throw specifier, you have to be sure that you really do want your program to die if it's violated. So, generally-speaking, it's best not to use them.

提交回复
热议问题