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

C++ C++;基类未捕获派生类异常,c++,exception,gcc4,C++,Exception,Gcc4,在我希望捕获异常的情况下,不会捕获异常。代码位于1 cpp文件中的1个函数中,该文件由GCC4.2编译成一个静态库,然后链接到Cocoa应用程序中。有问题的代码是 class runtime_error : public exception{ // More code }; int foo( void ){ try { if( x == 0 ){ throw std::runtime_error( "x is 0" ); }

在我希望捕获异常的情况下,不会捕获异常。代码位于1 cpp文件中的1个函数中,该文件由GCC4.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( … ){
    }
}
代码的第二个版本只解决运行时错误异常的问题,而不解决从std::exception派生的其他异常类的问题。你知道怎么了吗? 注意,代码的第一个版本在VisualStudio中运行良好

谢谢


Barrie

您的代码没有按编写的方式编译。当我按如下方式更改它以添加所需的include、变量等时,它会按预期打印“exception”(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;
}
#包括
#包括
#包括
int x=0;
int foo(无效){
试一试{
如果(x==0){
抛出std::runtime_错误(“x为0”);
}
}
捕获(标准::异常&e){
//我希望在这里能发现例外情况

std::cout您的类
runtime\u error
是在代码的命名空间中定义的类。我不确定您为什么要将它与
std::
一起用作范围解析运算符


throw std::runtime_error(“x为0”);
是否应更改为
throw runtime_error(“x为0”)

当一个类已经存在时,您定义自己的
运行时错误
类有什么原因吗?应该捕获异常。更新您的GCC,看看是否仍然发生错误您向我们展示的代码没有编译。请提供一个简短、自包含的完整示例。std::r的定义有一些混淆untime_错误。我实际上没有定义它。我只是表明它是从std::exception公开派生的,因此应该捕获异常。我发现是第三方库导致了这个问题。如果我链接库(但不调用它的任何代码)然后问题就出现了。如果我不链接第三方库,那么问题就不会发生。你知道链接第三方静态库会如何导致这个问题吗?谢谢,关于std::runtime_error的定义有些混乱。我实际上没有定义它。我只是表明它是从std::exception公开派生的下面是我刚刚测试过的一些代码,它以最初描述的方式运行并失败:#包括“stdafx.h”intfoo(void){try{throw std::runtime_error(“error”);return 0;}catch(std::exception&e){return 1;}catch(…){return 1;}