【发布时间】: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