无法捕获std :: runtime_error

Mat*_*ggs 1 c++ exception-handling exception c++11

也许我今天没有喝足够的咖啡.以下程序应该捕获std :: runtime_error并打印"我捕获了runtime_error",对吧?

它不是.这个程序没有捕获std :: runtime_error,而是打印"为什么我无法捕获runtime_error"?

我在这做错了什么?为什么我没有捕获std :: runtime_error?

这是Clang(参见下面代码的环境信息).

#include <iostream>
#include <exception>

int main(int argc, const char * argv[])
{
    try
    {
        throw new std::runtime_error( "a runtime_error was thrown" );
    }
    catch ( const std::runtime_error& e )
    {
        std::cout << "i caught the runtime_error" << std::endl;
    }
    catch ( ... )
    {
        std::cout << "why was i unable to catch the runtime_error?" << std::endl;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

OS X 10.9.5上的Xcode 5.1.1

comp:~ usrn$ clang --version
Apple LLVM version 5.1 (clang-503.0.38) (based on LLVM 3.4svn)
Target: x86_64-apple-darwin13.4.0
Thread model: posix
comp:~ usern$ 
Run Code Online (Sandbox Code Playgroud)

mel*_*k47 10

你在扔new std::runtime_error( "a runtime_error was thrown" );,

所以你扔了一个std::runtime_error*.

你可能想做throw std::runtime_error("..."),即按价值抛出.

  • 或者更好:*不*抛出堆分配的对象.按值引用,通过const引用捕获. (4认同)
  • 完全没有,只是陈述事实.但我可能应该澄清:) (2认同)