1
#include <iostream>    

struct ICantChange
{
    virtual ~ICantChange() {}
};

struct ClassThatThrows
{
    virtual ~ClassThatThrows() noexcept(false)
    {
        throw 44;
    }
};    

struct Test : ICantChange
{
    ~Test() 
    {
    }    
    ClassThatThrows instance;
};

main()
{
    try 
    {
        Test obj;
    }
    catch(int except)
    {
        std::cout << "caught" << std::endl;
    }
}

This code gives error message:

main.cpp:20:5: error: looser throw specifier for ‘virtual Test::~Test() noexcept (false)’
     ~Test()
     ^
main.cpp:6:13: error:   overriding ‘virtual ICantChange::~ICantChange() noexcept’
     virtual ~ICantChange() {}

To fix that error the only option I see is to add noexcept(false) to the destructor of class ICantChange that I cant because it is a library class.

I know that throwing destructors are bad but now I have Test class and I want to catch exceptions that are thrown when it is destructed.

Can anyone suggest a solution?

Ashot
  • 10,807
  • 14
  • 66
  • 117

1 Answers1

1

The issue you have is that destructor or noexcept(true), so by adding a member that is noexcept(false), you are breaking that promise.

But don't throw in destructors: throwing exceptions out of a destructor

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62