1

在析构函数中,有没有办法确定当前是否正在处理异常?

4

3 回答 3

7

您可以使用 std::uncaught_exception(),但它可能不会像您认为的那样做:有关更多信息,请参阅GoTW#47

于 2008-09-24T12:29:34.760 回答
2

正如 Luc 所说,您可以使用 std::uncaught_exception()。但你为什么想知道?在任何情况下,析构函数都不应该抛出异常

于 2008-09-24T14:53:05.070 回答
0

您可以使用Boost 测试库。看这里的一个小例子:

struct my_exception1
{
    explicit    my_exception1( int res_code ) : m_res_code( res_code ) {}
    int         m_res_code;
};


struct my_exception2
{
    explicit    my_exception2( int res_code ) : m_res_code( res_code ) {}
    int         m_res_code;
};

class dangerous_call {
public:
    dangerous_call( int argc ) : m_argc( argc ) {}
    int operator()()
    {
        if( m_argc < 2 )
            throw my_exception1( 23 );
        if( m_argc > 3 )
            throw my_exception2( 45 );
        else if( m_argc > 2 )
            throw "too many args";

        return 1;
    }

private:
    int     m_argc;
};


void translate_my_exception1( my_exception1 const& ex )
{
    std::cout << "Caught my_exception1(" << ex.m_res_code << ")"<< std::endl;
}


void translate_my_exception2( my_exception2 const& ex )
{
    std::cout << "Caught my_exception2(" << ex.m_res_code << ")"<< std::endl;
}



int 
cpp_main( int argc , char *[] )
{ 
    ::boost::execution_monitor ex_mon;
    ex_mon.register_exception_translator<my_exception1>(
        &translate_my_exception1);
    ex_mon.register_exception_translator<my_exception2>(
        &translate_my_exception2);
    try{
     // ex_mon.detect_memory_leak( true);
      ex_mon.execute( ::boost::unit_test::callback0<int>( 
          dangerous_call( argc ) ) );
    }   
    catch ( boost::execution_exception const& ex ) {
        std::cout << "Caught exception: " << ex.what() << std::endl;
    }
    return 0;
}

您必须深入研究文档。这是一个非常强大的库来测试你的软件!无论如何,在 Boost 的帮助下,您可以在功能测试的任何地方捕获任何类型的异常!

于 2008-09-24T12:57:07.020 回答