Skip to content

Destructor Throw

Exceptions should not be thrown by destructors.

What does this mean ?

When an exception is thrown, the call stack is unwound until the exception is handled. All automated objects declared between the point where the exception is thrown and when it is to be handled will have their destructors called.

What can happen ?

If one of these destructors throws an exception, the program will quit in an implementation-defined manner, which may result in unanticipated effects.

Recommendation

A destructor may throw an exception that is handled within the destructor, such as within a try-catch block.

Sample Code

Vulnerable :

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

Non Vulnerable :

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

References