繁体   English   中英

无法捕获std :: runtime_error

[英]Unable to catch a std::runtime_error

也许我今天没有喝咖啡。 以下程序应捕获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 std::runtime_error( "a runtime_error was thrown" );

因此,您将抛出std::runtime_error*

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM