mingw-gcc std::exception問題

在MSVC中拋出異常代碼如下:

#include <iostream>
#include <stdexcept>
#include <stdlib.h>

void exception_test()
{
    throw std::exception("exception_test EXCEPTION");
}
int main()
{
    try{
        exception_test();
    }
    catch(const std::exception& e)
    {
        std::cout<<e.what()<<std::endl;
    }
    catch(...){
        std::cout<<"exception catch...\n";
    }

    system("pause");
    return 0;
}

在main函數中可以正確的捕捉到std::exception異常,輸出:
> exception_test EXCEPTION

但是在mingw-gcc,exception_tes()函數不能編譯通過,

>  error: no matching function for call to 'std::exception::exception(const char [25])'

這是因爲使用的編譯器中std::exception根本就沒有std::exception(const char* )類似的構造函數;


爲了讓exception在msvc和mingw-gcc中都能編譯通過,修改exception_test()實現;

void exception_test()
{
    throw "exception_test STRING";
    throw std::runtime_error("exception_test RUNTIME_ERROR");
}
如果直接throw 字符串,main函數中輸出

> exception catch...

如果 throw std::runtime_error,效果和在msvc中使用throw std::exception效果一樣,

> exception_test RUNTIME_ERROR

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章