Should I place a try ... catch block in the destructor if I know that my function will not throw an exception

I know that a destructor should not throw an exception.

http://www.parashift.com/c++-faq-lite/dtors.html#faq-11.13

I have the following code:

~a()
{
    cleanup();
}

// I do not expect exception being thrown in this function.
// If exception really happen, I know that it is something not recoverable.
void a::cleaup()
{
    delete p;
}

In my static analysis of the source code, he complains that I will call the cleanup function as follows:

~a()
{
    try {
        cleanup();
    }
    catch(...) {
        // What to do? Print out some logging message?
    }
}

// I do not expect exception being thrown in this function.
// If exception really happen, I know that it is something not recoverable.
void a::cleaup()
{
    delete p;
}

I'm not sure if it is good practice to put a try ... catch block in a destructor, whenever it calls functions. How:

(1) If the cleanup function can throw an exception, I know something bad happened. I prefer it to be fail-fast . That is, just let the whole system crash, and let the programmer debug it.

(2) Overhead occurs when entering and exiting the try ... catch block.

(3) , ... .

, ... catch .

.

+3
6

delete , cleanup , , try-catch.

, , , , ( , ), cleanup no-throw.

void cleanup() throw();
+3

, . cleanup() , ? , , , - cleanup().

, , .

, () , . OutOfMemoryException , ? . , , . , , .

:

, cleanup, . delete p , a::cleanup , p .

+2

, p. cleanup()

delete p;

delete , p destructor. , try, , a.

+1

, , .

, , , , Symbian; , - . , , .

try {} catch(...) {} , , .

, , , , "cleanup()", "close()" "release_something().

try-catch. ++ ; , , (, , ).

+1

, - . , , - .

, , , , .

+1
source

I never use this, but purists will say that your function cleanup()can quit without expecting it. Thus, this scheme is a method of additional security.

However, the function cleanupshould not be rushed in the first place. Therefore, I would put any exception handling inside cleanup(), and not in the destructor itself.

0
source

Source: https://habr.com/ru/post/1724921/


All Articles