简体   繁体   English

无法捕获std :: runtime_error

[英]Unable to catch a std::runtime_error

Maybe I haven't had enough coffee today. 也许我今天没有喝咖啡。 The following program should catch the std::runtime_error and print "i caught the runtime_error", right? 以下程序应捕获std :: runtime_error并显示“我捕获了runtime_error”,对吗?

It is not. 它不是。 This program is not catching the std::runtime_error and is instead printing "why was i unable to catch the runtime_error"? 该程序未捕获std :: runtime_error,而是显示“为什么我无法捕获runtime_error”?

What am I doing wrong here? 我在这里做错了什么? Why am I not catching the std::runtime_error? 为什么我没有赶上std :: runtime_error?

This is Clang (see environment info below code). 这是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;
}

Xcode 5.1.1 on OS X 10.9.5 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$ 

You're throwing new std::runtime_error( "a runtime_error was thrown" ); 您正在抛出new std::runtime_error( "a runtime_error was thrown" ); ,

So you're throwing a std::runtime_error* . 因此,您将抛出std::runtime_error*

You probably want to do throw std::runtime_error("...") , ie throw by value. 您可能想要throw std::runtime_error("...") ,即按值抛出。

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

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