15.2 Constructors and destructors

15.2.1 Do not throw an exception from a destructor

The 2011 C++ Language Standard states that unless a user provided destructor has an explicit exception specification, one will be added implicitly, matching the one that an implicit destructor for the type would have received.

#include <stdexcept>
class A
{
public:
~A ()        // @@- Non-Compliant: Implicit destructor for A would be declared with -@@
             // @@-   noexcept, therefore this destructor is noexcept -@@
{
throw std::runtime_error ("results in call to std::terminate");
}
};

Furthermore when an exception is thrown, stack unwinding will call the destructors of all objects with automatic storage duration still in scope up to the location where the exception is eventually caught. The program will immediately terminate should another exception be thrown from a destructor of one of these objects.

#include <cstdint>
#include <stdexcept>
               
class A
{
public:
A () : m_p () {}
               
~A () noexcept(false)
{
if (nullptr == m_p)
{
throw std::runtime_error ("null pointer in A"); // @@- Non-Compliant -@@
}
}
                 
private:
int32_t * m_p;
};
               
void foo (int32_t i)
{
if (i < 0)
{
throw std::range_error ("i is negative");
}
}
               
void bar ()
{
try 
{
A a;
                   
foo (-1);
}
catch (std::exception const & e)
{
}
}

References

  • HIC++ v3.3 – 9.1

Click here for references