0

在我希望它们被捕获的情况下,异常不会被捕获。该代码位于 1 个 cpp 文件中的 1 个函数中,该文件由 GCC 4.2 编译为静态库,然后链接到 Cocoa 应用程序中。有问题的代码是

class runtime_error : public exception{
// More code
};


int foo( void ){
    try {
        if( x == 0 ){
            throw std::runtime_error( "x is 0" );
        }
    }
    catch( std::exception & e ){
    // I expect the exception to be caught here
    }
    catch( ... ){
        // But the exception is caught here
    }
}   

我可以将代码修改为

int foo( void ){
    try {
        if( x == 0 ){
            throw std::runtime_error( "x is 0" );
        }
    }
    catch( std::runtime_error & e ){
    // exception is now caught here
    }
    catch( … ){
    }
}

代码的第二个版本只解决了 runtime_error 异常的问题,而不解决可能从 std::exception 派生的其他异常类的问题。知道有什么问题吗?请注意,代码的第一个版本适用于 Visual Studio。

谢谢,

巴里

4

2 回答 2

1

您的代码未按书面方式编译。当我如下更改它以添加所需的包含、变量等时,它会按预期打印“异常”(g++ 4.2 和 4.5)。您能否向我们展示导致您的问题的完整真实代码?

#include <exception>
#include <stdexcept>
#include <iostream>

int x = 0;

int foo( void ){
    try {
        if( x == 0 ){
            throw std::runtime_error( "x is 0" );
        }
    }
    catch( std::exception & e ){
        // I expect the exception to be caught here
        std::cout << "exception" << std::endl;
    }
    catch( ... ){
        // But the exception is caught here
        std::cout << "..." << std::endl;
    }

    return 0;
}

int main()
{
    foo();

    return 0;
}
于 2012-02-13T18:17:36.513 回答
0

您的类runtime_error是在代码的命名空间中定义的类。我不确定您为什么将它std::用作范围解析运算符?

该行不throw std::runtime_error( "x is 0" );应该更改为throw runtime_error( "x is 0" );吗?

于 2012-02-13T21:09:21.960 回答