throwing exceptions out of a destructor

后端 未结 16 2178
暗喜
暗喜 2020-11-22 00:23

Most people say never throw an exception out of a destructor - doing so results in undefined behavior. Stroustrup makes the point that \"the vector destructor e

16条回答
  •  日久生厌
    2020-11-22 01:14

    Unlike constructors, where throwing exceptions can be a useful way to indicate that object creation succeeded, exceptions should not be thrown in destructors.

    The problem occurs when an exception is thrown from a destructor during the stack unwinding process. If that happens, the compiler is put in a situation where it doesn’t know whether to continue the stack unwinding process or handle the new exception. The end result is that your program will be terminated immediately.

    Consequently, the best course of action is just to abstain from using exceptions in destructors altogether. Write a message to a log file instead.

提交回复
热议问题