【问题标题】:Unable to catch a std::runtime_error无法捕获 std::runtime_error
【发布时间】:2015-08-20 17:58:42
【问题描述】:

也许我今天没有喝足够的咖啡。下面的程序应该会捕获 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;
}

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$ 

【问题讨论】:

  • 你不应该在这里使用new
  • 出于某种原因,我认为需要堆分配异常。我不知道我是怎么想到的。

标签: c++ c++11 exception exception-handling


【解决方案1】:

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

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

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

【讨论】:

  • 是的。那很快。谢谢。
  • 或者更好:抛出一个堆分配的对象。按值抛出,按常量引用捕获。
  • 您是否建议他们继续使用new
  • 完全没有,只是陈述事实。但我可能应该澄清:)
  • melak47,您应该在答案的末尾添加不使用堆分配抛出的建议。谢谢!
猜你喜欢
  • 1970-01-01
  • 2011-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-06
  • 1970-01-01
  • 2020-07-23
相关资源
最近更新 更多