Say I have this code:
class Foo {
public:
Foo() {};
~Foo() {
// Some code
if (error_that_should_never_ever_happen)
throw SomeException("Some error message");
// Some code
}
};
In c++11 and above destructors have noexcept(true) so if error_that_should_never_ever_happen does happen SomeException couldn't be caught and the program would be terminated because of uncaught exception which is great because that's what I want (if error_that_should_never_ever_happen does happen then it's really bad).
But I want to test the code so I have this test:
Foo* f = new Foo();
try {
// Some alien code that will create a error_that_should_never_ever_happen in ~Foo()
delete f;
assert(false);
} catch(SomeException& ex) {
assert(true);
}
What is the best thing to do:
- To remove both the if(error_that_should_never_ever_happen) and the test for it which will create undefined behavior if error_that_should_never_ever_happen.
- To remove only the test so I would have untested code (why test something that should never ever happen)
- To declare the destructor with noexcept(false) which will create problems if the code is reused by somebody else and the exception is caught.
To compile the application with a flag -DTEST_ENABLED if I also compile the test (which I allready do) and to make Foo look like this:
#ifndef TEST_ENABLED #define FAIL_SAFE_FOO_DESTRUCTOR true #else #define FAIL_SAFE_FOO_DESTRUCTOR false #endif // TEST_ENABLED class Foo { public: Foo() {}; ~Foo() noexcept(FAIL_SAFE_FOO_DESTRUCTOR) { // Some code if (error_that_should_never_ever_happen) throw SomeException("Some error message"); // Some code } };
which will make the code less readable and less portable.
I'm open for more elegant solutions.