'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;
}
}
Solution 1:[1]
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 actually strings. A string literal allocates some static storage for the contents of the string, and evaluates as a const char (&)[N]
type, i.e. 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");
Solution 2:[2]
this should work
try {
throw (std::string)"connection fail";
} catch( string e ) {
if(e == "connection fail") {
std::cout << "caught: " << e << std::endl;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Remy Lebeau |
Solution 2 |