簡體   English   中英

C ++派生類異常未被基類捕獲

[英]C++ derived class exception not caught with base class

在我希望捕獲異常的情況下,不會捕獲異常。 該代碼位於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中正常工作。

謝謝,

巴里

您的代碼未按書面要求進行編譯。 當我按如下所示更改它以添加所需的包含項,變量等時,它將按預期方式打印“ 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;
}

您的類runtime_error是在代碼的名稱空間中定義的類。 我不確定為什么將std::作為范圍解析運算符使用它?

該行不應該throw std::runtime_error( "x is 0" ); 更改為throw runtime_error( "x is 0" );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM