简体   繁体   中英

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?

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"?

What am I doing wrong here? Why am I not catching the std::runtime_error?

This is Clang (see environment info below code).

#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

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" ); ,

So you're throwing a std::runtime_error* .

You probably want to do throw std::runtime_error("...") , ie throw by value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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