简体   繁体   中英

Why does string not work here while char const* does?

Why does string not work here when I catch an error, and char const* does? What is the difference between the two?

try {
    throw "connection fail";

} catch( string e ) {
    if(e == "connection fail") {
        std::cout << "caught: " << e << std::endl;
    }
}

You're not throwing a std::string, so you can't catch one.

Why is that not a string?

Because in C++, the perfidiously-misnamed string literals (that's what "abc" is) are not strings. A string literal allocates some static storage for the contents of the string, and evaluates as a const char (&)[N] type, ie a reference to an array of characters of a given fixed length. In most contexts, that reference decays to a const char * , which is a pointer to a const char, and has nothing to do with strings in any sensible interpretation of the term "string". This is an unfortunate legacy of C, where there were no strings either, and you passed a "string" by passing a pointer to the first character of a string, with the implicit assumption that the string has to be '\0' -terminated and of course couldn't contain NUL's ( '\0' ) since they were indistinguishable from a terminator.

To create a string, you must be explicit about it: throw std::string("foo bar baz");

this should work

try {
    throw (std::string)"connection fail";

} catch( string e ) {
    if(e == "connection fail") {
        std::cout << "caught: " << e << std::endl;
    }
}

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