Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I add throw() to the declarations for my C++ destructors?

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

like image 660
e.James Avatar asked Jan 19 '09 06:01

e.James


1 Answers

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.

like image 107
Rob Kennedy Avatar answered Oct 02 '22 15:10

Rob Kennedy