views:

324

answers:

2

I have seen some C++ classes with a destructor defined as follows:

class someClass
{
    public:
        someClass();
        ~someClass() throw();
};

Is this a good idea?

I am well aware that destructors should never throw exceptions, but will this actually prevent me from throwing exceptions in my destructors? I'm not 100% sure what it guarantees.

Reference: this recent question

+3  A: 

It's not an awful idea. If you throw in the dtor while no exception is being propagated, you will abort immediately which lets you know you've forgotten to make an actual non-throwing dtor.

If on the other hand you leave the throw spec out, you'll only know about your bad dtor implementation when an exception is, in fact, thrown.

+7  A: 

It does not prevent you from throwing exceptions from your destructor. The compiler will still let you do it. The difference is that if you do allow an exception to escape from that destructor, your program will immediately call unexpected. That function calls whatever unexpected_handler points to, which by default is terminate. So unless you do something to handle an unexpected exception, your program terminates, which isn't altogether a bad idea. After all, if the exception really is unexpected, then there's not really anything your program would be able to do to handle it anyway.

This isn't something special about destructors; the same rules apply to exception specifications for all methods.

Rob Kennedy