如何测试抛出异常C ++的析构函数

时间:2017-10-22 13:33:11

标签: c++ c++11

说我有这段代码:

class Foo {
public:
    Foo() {};
    ~Foo() {
        // Some code
        if (error_that_should_never_ever_happen)
            throw SomeException("Some error message");
        // Some code
    }
};

在c ++ 11及更高版本中,析构函数有noexcept(true)所以如果error_that_should_never_ever_happen确实发生,则无法捕获SomeException,并且由于未捕获的异常而终止程序,因为这是我想要的(如果error_that_should_never_ever_happen确实发生了)那真是太糟糕了。)

但我想测试代码,所以我有这个测试:

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);
}

最好的事情是什么:

  1. 要删除if(error_that_should_never_ever_happen)及其测试,如果error_that_should_never_ever_happen将会创建未定义的行为。
  2. 只删除测试,以便我有未经测试的代码(为什么要测试一些永远不会发生的事情)
  3. 使用noexcept(false)声明析构函数,如果代码被其他人重用并且捕获到异常,则会产生问题。
  4. 如果我还编译了测试(我已经做过)并使Foo看起来像这样,那么用标志-DTEST_ENABLED编译应用程序:

    #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
        } 
    };
    
  5. 会降低代码的可读性和便携性。

    我愿意接受更优雅的解决方案。

0 个答案:

没有答案
相关问题