Skip to content

Destructor Throw

Destructors should not throw exceptions

What does this mean ?

When an exception is thrown, the call stack is unwound up to the point where the exception is to be handled. The destructors for all automatic objects declared between the point where the exception is thrown and where it is to be handled will be invoked.

What can happen ?

If one of these destructors exits with an exception, then the program will terminate in an implementation-defined manner, potentially yielding unexpected results.

Recommendation

It is acceptable for a destructor to throw an exception that is handled within the destructor, for example within a try-catch block.

Sample Code

Vulnerable :

class MyClass
{
    ~MyClass()
    {
        throw new NotImplementedException(); // Noncompliant
    }
}

Non Vulnerable :

class MyClass
{
    ~MyClass()
    {
        // no throw
    }
}

References