基类未捕获 C++ 派生类异常

标签 c++ exception gcc4

在我希望异常被捕获的情况下,异常没有被捕获。代码在 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 中运行良好。

谢谢,

巴里

最佳答案

您的代码无法按照编写的方式进行编译。当我如下更改它以添加所需的包含、变量等时,它会按预期打印“异常”(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;
}

关于基类未捕获 C++ 派生类异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9265329/

相关文章:

c++ - 如何为子函数指定模板参数?

c++ - 自定义返回类型声明

c++ - Boost C++ Phoenix 用户定义参数的下标运算符 [] 错误

linux - 在 Linux 上构建 FBX SDK

c - 为什么 gcc4 不展开这个循环?

c++ - 使用 getaddrinfo() C 函数获取本地 IP 地址?

python - 在 Windows 上使用 Python 解决伪造的 OSError, 13 (EACCES) 的好方法是什么

apache-spark - Spark : load or select Hive table of ORC format

spring - 无法重启 Liferay : numerous BeanCreationException-s

c++ - C-回调函数模板 : explicitly instantiate template