2017-09-26 87 views
0

我已经抛出一个std::ios_base::failure并试图抓住它,在C++ 11模式中使用铛4.0以下示例代码:为什么叮当4.0不捕捉std异常?

#include <ios> 
#include <iostream> 
#include <stdexcept> 

int 
main() 
{ 
    try { 
    throw new std::ios_base::failure("Bonkers"); 
    } 
    catch(std::ios_base::failure &e) { 
    std::cout << "Failure " << e.what() << std::endl; 
    } 
    catch(...) { 
    std::cout << "Anything" << std::endl; 
    } 
    return 0; 
} 

予编译程序这样的:

clang++-4.0 --std=c++11 -g -W -Wall ex.cc -o ex 

而我得到的输出:

Anything 

我会期待它捕捉到特定的异常。我尝试了g ++ 5.4,但结果相同。也尝试没有C + + 11标志,也没有帮助。拿出catch all条款给我这个:

terminate called after throwing an instance of 'std::ios_base::failure[abi:cxx11]*' 

那么我错过了什么,我能做些什么来解决这个问题?当我不使用C++ 11标志时,abi:cxx11也显示出来。

+8

你正在抛出一个'std :: ios_base :: failure *'并试图捕获一个'std :: ios_base :: failure'。那些不是同一类型。 – nwp

+2

更改'抛出新的std :: ios_base :: failure(“Bonkers”);'抛出std :: ios_base :: failure(“Bonkers”);' –

+3

你的意思是抛出std :: ios_base :: failure(“ Bonkers“);' –

回答

1

正如在注释中提到的那样,在C++中,您不需要通过new来分配异常,因此将指针指向异常,就像在Java中所做的那样。

相反,你只需构造异常,并把它:

throw std::ios_base::failure("Bonkers"); 

然后类型的catch子句将匹配,并计划将像预期的那样。